Recognizing interfaces while using reflection


Big Daddy

I have an interface called PeriodicJob. In a DLL, I declare the
interface and then create a class that implements the interface. In a
different executable, I also declare the interface. I then load the
assembly with late binding and create an instance of the class with
reflection. I try to cast the object to the class type of the
interfact, but I get an invalid cast exception. It says that the
object I am creating isn't a PeriodicJob. But the class does
implement the PeriodicJob interface. I am guessing the reason it
doesn't work is because when I declare the interface in the DLL and
then declare it again in the EXE, even though they have the same name
and structure, they are considered to be two different interfaces.
Here's the code where I use reflection:

Assembly a = Assembly.LoadFrom(path + "\\" +
Object obj = a.CreateInstance(className);
PeriodicJob pj = (PeriodicJob)obj;

How do I make it such that both the DLL and the EXE use the same
actual interface? Do I have to declare the interface in a totally
different DLL and then reference that DLL from both my EXE and DLL
that has the implementation?

thanks in advance,



Marc Gravell

..NET types are always scoped by their assembly. So yes; even if two
projects use the same .cs file, they are two different .NET types, and
cannot be cast to eachother. For runtime purposes, the trick is to
place the code into an assembly that both of your *actual* assemblies
can see. This might be a new dll, or it could just be that the exe
references the dll (and place the interface in the dll).

For serialization purposes, the best approach (for scenarios where it
must be interoperable with different clients) is to use something that
doesn't depend on .NET types - so BinaryFormatter might be
inappropriate, but XmlSerializer / DataContractSerializer / bespoke
might be viable options.


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