Search code examples
c#mef

Handle ReflectionTypeLoadException during MEF composition


I am using a DirectoryCatalog in MEF to satisfy imports in my application. However, there are sometimes obfuscated assemblies in the directory that cause a ReflectionTypeLoadException when I try to compose the catalog.

I know I can get round it by using a separate directory or by using a search filter on the DirectoryCatalog but I want a more general way to solve the problem. Is there some way I can handle the exception and allow composition to continue? Or is there another more general solution?


Solution

  • DirectoryCatalog already has code to catch ReflectionTypeLoadException and ignore those assemblies. Unfortunately, as I have reported, merely creating the AssemblyCatalog will not yet trigger the exception so that code doesn't work.

    The exception is actually triggered by the first call to AssemblyCatalog.Parts.

    Instead of using the DirectoryCatalog from MEF, you will have to do it yourself:

    • scan a directory for assemblies
    • load each assembly and creates a AssemblyCatalog for it
    • invoke AssemblyCatalog.Parts.ToArray() to force the exception, and catch it
    • aggregate all the good catalogs with a AggregateCatalog