views:

135

answers:

2

When running the below code a type is never returned, despite there being a class with the correct attribute assigned. In fact the attr array always has a length of 0.

Assembly a = Assembly.LoadFile(file);
foreach (Type t in a.GetTypes())
{
    object[] attr = t.GetCustomAttributes(typeof(SchemeNameAttribute), false);

    foreach (object attribute in attr)
    {
        SchemeNameAttribute schemeName = attribute as SchemeNameAttribute;
        if (schemeName != null && schemeName.Name.ToLower() == brickName.ToLower() )
        {
            return t;
        }
    }
}

if I change it to use:

object[] attr = t.GetCustomAttributes(false);

then it picks up one custom attribute of type SchemeNameAttribute for the Type, but

SchemeNameAttribute schemeName = attribute as SchemeNameAttribute;

always returns a null value for schemeName.

Any ideas?

A: 

I suspect you have re-declared the attribute - i.e. the SchemeNameAttribute type is declared (separately) in two assemblies (perhaps by copying a .cs). This will not work; types are scoped by their assembly, so SchemeNameAttribute in Foo.dll is a different type to SchemeNameAttribute in Bar.dll/Bar.exe.

You should ensure that the SchemeNameAttribute type is declared once only - if necessary, by moving it to a dll that both the existing assemblies can reference.

Marc Gravell
+2  A: 

You mixed two different contexts of loading assemblies: "Load Context" in which your application is running, and "No context" in which you load secondary assembly from using LoadFile. You want to read this and that articles to get an idea about loading contexts. The most important part here is that assemblies loaded into different contexts, even from the same location, are considered different. And thus types in them are considered different. So, type SchemeNameAttribute in your loaded assembly is not the same, as the type SchemeNameAttribute in application.

Ilya Ryzhenkov