10

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)

?

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
Marc Wittke
  • 2,991
  • 2
  • 30
  • 45

6 Answers6

5

It is possible to load (reflection only) assemblies with dependencies.

AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += (s, e) => Assembly.ReflectionOnlyLoad(e.Name);

would fix failures when loading, assuming they are all in the same folder.

Aykut Kllic
  • 898
  • 9
  • 14
  • Can you elaborate with a better answer here? It sounds like you found a work around... But I can't make it work. – Vaccano Nov 15 '11 at 22:30
  • 1
    This is not a workaround but a valid solution. When the assembly containing the required types cannot be discovered in reflection-only context, the `ReflectionOnlyAssemblyResolve` event is fired. You can manually load the assembly then. – paulius_l Oct 08 '12 at 14:23
4

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.

Marc Wittke
  • 2,991
  • 2
  • 30
  • 45
3

Really old question, but this has been possible since .NET 2.0. The problem is that everything loaded into the reflection-only load context is implemented so that you cannot accidentally trigger loading the assembly into the current AppDomain. Reflecting over the custom attribute types defined in the assembly is one of these.

You would need to use CustomAttributeData to view these custom attributes.

var assy = Assembly.ReflectionOnlyLoadFrom("MuhPlugin.dll");
// gets assembly-level attributes, but you get the idea
var attrs = CustomAttributeData.GetCustomAttributes(assy);

CustomAttributeData instances contain information about the attribute, including its Type, constructor parameters and named parameters. Note that the Types in the object graph are reflection-only, so if you try to do things with them that would trigger loading an assembly it'll throw the familiar exception.

You can use this metadata about your metadata to determine if the reflected assembly qualifies for whatever your needs are.

2

Have you looked at the microsoft AddIn Framework.

It allows for loading modules (AddIns) in the different app domains and processes, and querying by interface on specific attribute data.

It might not be what you want, but could be worth a look.

http://msdn.microsoft.com/en-us/library/bb384200.aspx

string[] warnings = AddInStore.Update(Environment.CurrentDirectory);
Collection<AddInToken> tokens = AddInStore.FindAddIns(typeof(YourType), Environment.CurrentDirectory)

AddInEnvironment addInEnvironment = new AddInEnvironment(AppDomain.CurrentDomain);
YourType module = tokens[0].Activate<YourType>(addInEnvironment);

And with a bit of LINQ you can query it

AddInToken myToken = tokens.FirstOrDefault(currentAddInToken => currentAddInToken.Name.Equals(moduleName))
monkey_p
  • 2,849
  • 2
  • 19
  • 16
  • MAF or even MEF seems to be an option, yes. Unfortunately this would require a change in the design of the plugin, which is not directly (and not mandatory) developed by us. – Marc Wittke Sep 22 '09 at 12:04
  • It could be a problem if the plugin isn't easily wrapable – monkey_p Sep 22 '09 at 12:10
  • But i suppose wraping it would defy your need if the external plugins need to be recompiled by you – monkey_p Sep 22 '09 at 12:11
2

If you are remoting or using a proxy configuration, you will have something similar to this:

AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += (s, e) => OnReflectionOnlyResolve(e, directory); 

However, if you are getting an exception across the domain, it probably looks like this:

{System.InvalidOperationException: It is illegal to reflect on the custom attributes of a Type loaded via ReflectionOnlyGetType (see Assembly.ReflectionOnly) -- use CustomAttributeData instead.

Here is the code that will trigger that off the 1st line.

object[] attributes = assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
return attributes.Length == 0 ? "" : ((AssemblyTitleAttribute) attributes[0]).Title;

You will need to change it to use CustomAttributeData like this:

foreach (CustomAttributeData cad in assembly.GetCustomAttributesData().Where(a => a.AttributeType == typeof (AssemblyTitleAttribute)))
  return cad.ConstructorArguments.FirstOrDefault().Value as String;
return String.Empty;
Latency
  • 426
  • 3
  • 12
1

If I were you I'd cache assembly metadata in, for instance, XML files. Using this approach you completely eliminate a need to load anything. And you can store even information, to calculate which you need to perform a time-consuming operation.

You can have XML files pregenerated or generated on-the-fly by scanning all existing assemblies.

Vladislav Rastrusny
  • 29,378
  • 23
  • 95
  • 156
  • 1
    Don't like this approach, because it relies on additional metadata. This is not much better than hard coding in which directory an assembly with fixed file name must be located. – Marc Wittke Sep 22 '09 at 12:06
  • It relies on cached metadata, not additional. You extract metadata from assemblies and store them in your cache (XML files or whatever). It is faster and better then reading assemblies. Also, this approach is much more extensible because after some time you will end up with something, you will not be able to extract from assembly without loading it. – Vladislav Rastrusny Sep 22 '09 at 12:41
  • 1
    Maybe I don't get you, but who is creating the metadata cache? It requires either the creator to provide a valid metadata description or me to create it somewhat earlier before attempting to load the module. In both ways, someone will need to do this and the problem is exactly the same – Marc Wittke Sep 23 '09 at 08:02
  • "or me to create it somewhat earlier before attempting to load the module" - YES. And you need to do that just once. For example, during software installation. After that there is no performance impact as you read metadata from the cache you generated. – Vladislav Rastrusny Sep 23 '09 at 08:24