Search code examples
c#pluginsassembliesattributes

How to get custom attributes from an assembly that is not (really) loaded


We all know that the assembly can be queried for attributes using the GetCustomAttributes method. I want to use this to identify an extension module for my application. However, to avoid loading every assembly I prefer a defensive approach:

  1. using Assembly.ReflectionOnlyLoadFrom to get more details about an assembly (has it my ModuleAttribute?)

  2. if the ModuleAttribute is found, I will finally load it using Assembly.LoadFrom

Unfortunately it seems that there is no way to get the attributes from an assembly, that is loaded into the reflection-only context:

myAssembly.GetCustomAttributes(typeof(ModuleAttribute), false)

fails with an InvalidOperationException

It is illegal to reflect on the custom attributes of a Type loaded via ReflectionOnlyGetType

and

CustomAttributeData.GetCustomAttributes(myAssembly)

fails with ReflectionTypeLoadException because of dependant assemblies not being loaded.

So how to get the attributes without

  1. polluting my application domain with useless (maybe harmful) types by calling Assembly.LoadFrom
  2. the need to load all referenced assemblies
  3. the need for separate application domains (gave it a short try, smelled like even more PITA)

?


Solution

  • After checking all answers and doing some more research, it seems that there is simply no way to do what I want: check if an assembly is a valid extension module before loading it into the application domain.

    Either I have to load the assembly that should be inspected into another application domain, inspect it there and when it succeeds load it again into my current application domain or I need to store metadata of the assembly outside the assembly itself and trust this metadata. Option one is not possible because of architectural restrictions, option two just shifts the problem but not solves it.

    Probably the best alternative is to use the Managed Extensibility Framework, but this is unfortunately not that easy in the current setup.

    I end up with trusting that there is nothing "bad" in the modules directory and loading everything (with some checks for not exceeding a maximum file size and not being loaded already).

    Nevertheless, thank you for your ideas.