Casting a class/Interface using createInstance

G

Guest

I am having a problem where I create an instance of a class from an assembly
and I try to cast it to an interface that it inherits from and it says that
the cast is invalid.

Here is the code:

Interface.IParser objPlugin;
Interface.PluginServices parserService = new Interface.PluginServices();
objPlugin = (Interface.IParser)parserService.CreateInstance(_parser);
return objPlugin.ParserName;

the CreateInstance above is a function that calls Assembly.LoadFrom and then
subsequently createInstance. Everything in that function seems to operate
normally returning an instance of my class that is contained in the assembly
testParser.TestParser which implements Interface.IParser which is an
interface class that I wrote.

The problem is that the line
"objPlugin = (Interface.IParser)parserService.CreateInstance(_parser);"
causes an invalid cast exception.
 
G

Guest

Your right that article does seem to apply but then how come this works.

Interface.PluginServices.AvailablePlugin pars = new
Interface.PluginServices.AvailablePlugin();
pars.AssemblyPath = "C:\\Projects\\testParser\\bin\\Debug\\testParser.dll";
pars.ClassName = "testParser.TestParser";
Interface.IParser mytest = myP.CreateInstance(pars) as Interface.IParser;

where myP.CreateInstance is :
Assembly objDLL;
object objPlugin;
//load dll
objDLL = Assembly.LoadFrom(Plugin.AssemblyPath);
//create and return class instance
objPlugin = objDLL.CreateInstance(Plugin.ClassName);
return objPlugin;
 
G

Guest

Sorry I didn't explain this better but Interface.IParser is a statically
referenced dll and you can see below that I am casting it to the reference
created from my loadFrom which is a different dll but implements
Interface.IParser

I guess I'm not sure what to do because my intention is to have my
Interface.dll in several different projects so that I can ensure if I load
one of my parsing dll's that they are implementing the correct Interface.

Thanks for your help
 
G

Guest

I haven't heard anything from my last post I'm still unclear as to what is
going on in my code
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top