Problems finding an attribute attached to a type

When you run the code below, the type is never returned despite the presence of a class with a matching attribute assigned. In fact, the attr array is always 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 changed it to use:

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

      

then it selects one custom attribute of type SchemeNameAttribute for Type, but

SchemeNameAttribute schemeName = attribute as SchemeNameAttribute;

      

always returns null for schemName.

Any ideas?

0


source to share


2 answers


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



+2


source


I suspect you have re-declared the attribute, that is, the SchemeNameAttribute type is declared (separately) in two assemblies (possibly by copying the .cs). This won't work; types are tied to their assembly, so the SchemeNameAttribute in Foo.dll is a different type for the SchemeNameAttribute in Bar.dll / Bar.exe.



You must ensure that the SchemeNameAttribute type is declared once — if necessary, by moving it into a dll that can be referenced as existing assemblies.

0


source







All Articles