views:

196

answers:

2

I have an application that loads assemblies and looks for types that are subclasses of a class C1 defined in another assembly A1 that the application references. I've defined a type T in A1 that is a subclass of C1 but when I load A1 using Assembly.Load(...) then call t.IsSubclassOf(typeof(C1)) on an instance of T I get false. I've noticed that there are 2 instances of the assembly A1 in the current appdomain and t.IsSubclassOf(C1) works if I grab the type C1 out of one of the instances but not both. I don't quite understand this behavior, can anyone explain? Futhermore how can I fix my app so that this works whether load A1 or some other assembly to look for subtypes of C1?

+2  A: 

In order for the CLR to uniquely identify types, it includes assembly information in the type identifier. Your problem is that the CLR is classifying the two instances of A1 as different assemblies, hence you are effectively executing:

A1::T1.IsSubClassOf(A1Copy::C1)  // No relationship between A1 and A1Copy

... instead of:

A1::T1.IsSubClassOf(A1::C1)

An assembly is uniquely identified by its name, version, culture, and public key. Please check these values (via Assembly.GetName()) from both assembly instances in the app-domain; I suspect there is a mismatch in one of the attributes, which is causing the CLR to load the offending assembly.

Steve Guidi
It is based on the Load Context why he's getting them as not equal. http://blogs.microsoft.co.il/blogs/sasha/archive/2007/03/06/Assembly-Load-Contexts-Subtleties.aspx
sixlettervariables
+1  A: 

Yeah, i just built two projects with this, I defined in one project parent and child classes:

namespace ClassLibrary1
{
    public class Parent
    {
        public string name;
    }

    public class Child : Parent
    {
    }
}

and then tried to load the information:

 {
        Type parent = typeof(Parent);
        Type c1 = typeof(Child);
        bool isChild1  = (c1.IsSubclassOf(parent).ToString());

        Assembly a = Assembly.Load(File.ReadAllBytes("ClassLibrary1.dll"));
        Type c2 = a.GetType(c1.FullName);
        bool isChild2 = (c2.IsSubclassOf(parent).ToString());
    }

and I got isChild1 being true and isChild2 being false.

Checking out this link by Suzanne Cook on Loading Contexts provided some more light:

http://blogs.msdn.com/suzcook/archive/2003/06/13/57180.aspx

Irwin