views:

162

answers:

2

I've run into this apparently not uncommon problem --

  1. I have a interface in Assembly A.

  2. I am dynamically loading Assembly B, and trying to cast an object from it into my interface from Assembly A.

  3. It's failing with an InvalidCastException.

I've come to understand why -- a class in Assembly A and a class in Assembly B, even with the same name and the same code, are not the same thing and cannot be cast to one another.

My question is: is there a solution to this? Is there any way I can make the two types compatible, or do I need to duplicate my interface in Assembly B and cast the object to that?

I'm loading Assembly B with Assembly.LoadFrom -- is there a different way to do that which would make them type-compatible?

I can't be the first person to have this problem. What I'm trying to do would seem like a fairly common task with plugin architectures.

+6  A: 

Duplicating is not the answer. Can Assembly B possibly reference Assembly A and consume the interface (or whatever) from there?

If not, declare the interface (or whatever) in a standalone dll that both Assembly A and Assembly B reference. Then there is only 1 version of the interface, and everything works.

Marc Gravell
That is what I had to do also..
RobS
+2  A: 

You can definitely cast from a type in one assembly to a type in another - otherwise we could never cast down from object :)

I suspect the problem is that the interface has been loaded separately - I suspect that your Assembly B has loaded Assembly A again (possibly from somewhere else?).

What does your file layout look like? If you're loading Assembly B from a different directory and it has a copy of Assembly A in its directory, it may be loading it from there. Assembly loading and binding is a tricky business. I recommend getting hold of "CLR via C#" and reading the chapter on it very carefully, and/or turning on Fusion logging to see what's going on.

(I'm assuming that the type in assembly B really does implement the interface in assembly A, by the way? If not, that would explain it!)

I have a fairly old article which acts as a sort of tutorial for this, by the way. It may help.

Jon Skeet