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?
I was doing this from an API I was writing and the SafeDirectoryCatalog would not log multiple exports matching a single import from different assemblies. MEF debugging is typically done via debugger and TraceListener. I already used Log4Net and I didn't want someone to need to add another entry to the config file just to support logging. http://blogs.msdn.com/b/dsplaisted/archive/2010/07/13/how-to-debug-and-diagnose-mef-failures.aspx I came up with:
To save others from writing their own implementation of the SafeDirectoryCatalog, here is the one I came up with based upon Wim Coenen's suggestions:
DirectoryCatalog
already has code to catchReflectionTypeLoadException
and ignore those assemblies. Unfortunately, as I have reported, merely creating theAssemblyCatalog
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:AssemblyCatalog
for itAssemblyCatalog.Parts.ToArray()
to force the exception, and catch itAggregateCatalog