Updated 5/27/2015
We just found out that MEF of .NET 4 leaks memory due to the container never removes the reference. We found that our application memory usage kept increasing and at the end it ran out of memory. The details of why and how to avoid is described here. http://toreaurstad.blogspot.com/2012/09/freeing-up-memory-used-by-mef.html. He also describes how MEF2 under .NET4.5 can solve the memory leak http://toreaurstad.blogspot.no/2013/07/mef-and-memory-in-mef-2.html.
Sometimes you cannot use the assemblies in the executing directory.I wanted to resolve export only from a particular assembly.
[Import]
IStatusLogger statusLogger = null;
...
AggregateCatalog agg = new AggregateCatalog();
var statusCatalog = new AssemblyCatalog(typeof(ConsoleStatusLogger).Assembly);
var container = new CompositionContainer(agg);
try
{
statusLogger = container.GetExportedValue<IStatusLogger>();
}
catch(Exception ex)
{
var typeLoadException = ex as ReflectionTypeLoadException;
var loaderExceptions = typeLoadException.LoaderExceptions;
foreach (var item in loaderExceptions)
{
Trace.WriteLine(item.Message);
}
}
When I composing the exported object and try to get the import resolved, I got
the following exception message:
Unable to load one or more of the requested types. Retrieve the LoaderExceptions
property for more information.
It turned out thatin order to retrieve the LoaderExceptions, you have to know how to cast
the exception object into the right object. Here is how.
using System.Reflection;
...
try
{
}
catch (Exception ex)
{
var typeLoadException = ex as ReflectionTypeLoadException;
var loaderExceptions = typeLoadException.LoaderExceptions;
string msg = string.Empty;
foreach (var item in loaderExceptions)
{
msg += item.Message;
msg += "\n";
}
// show message here
}