tags:

views:

101

answers:

2

I'm looking for an explanation for the following - I have an assembly I'm loading using

Assembly assembly = Assembly.LoadFrom(filename);

I then loop on all the types in the assembly, and wish to try and find out if a type implements a particular interface and if so I want an instance of that type, I've tried several things which did not work, but when I fell back to the most basic (and probably inefficient) way, I realised there's something more fundamental I don't understand -

            foreach (Type t in assembly.GetTypes())
            {
                foreach (Type i in t.GetInterfaces())
                {
                    if (i.FullName == pluginInterfaceType.FullName)
                    {
                        object o = assembly.CreateInstance(t.ToString());
                        IInterface plugin = (IInterface)o;

That last line causes an InvalidCastException, despite the fact that the type created definitely implements that interface.

Further more - if I use Activator.CreateInstance instead of Assembly.CreateInstance (which I don't want to do), casting to the interface works just fine.

A: 

The InvalidCastException should contain more details, like 'cannot cast x to y'.
My guess is that the assembly containing IInterface that you are loading is not exactly the same as the one your code was built against, maybe it's a local copy of a non strongly-named assembly.

Paolo Tedesco
+1  A: 

This is most probably because the interface you are casting to is not the same you find in the class.

Either because there is more the one interface with the same name, or because you loaded it more then once. For instance, because it is defined in the assembly you are dynamically loaded, and you try to cast it to the one that is statically bound.

Stefan Steinegger
That might be a direction, I could use a little bit more detail - There are three assemblies involved - I have a shared assembly which defines the interfaces, I then have an exe which dynamically loads a third assembly (using the CreateInstance).both the exe and the dll reference the shared assembly with the interfaces. As far as I can see the interface definition is the same, the fact is that I've managed to compare it with the full name successfully, and I don't believe I've defined it in two places with the same name.
Yossi Dahan
You can load an type dynamically, then it is not the same as the type you are statically bound to. Even if it is actually the same code.
Stefan Steinegger
So what you're saying is that as I loaded the interface statically (project reference) and then also loaded dynamically an assembly that has its own [same project] reference, these are considered different types?How come it works well when using the Activator then?
Yossi Dahan