Search code examples
.netpluginsmef

MEF Assembly loading from cache?


I got an application that load plugins via MEF.

The application is running in several instances on a terminal server.

When I need to test a new plugin in the production environment I redirect MEF to another folder. The problem is that sometimes the assemblies are loaded from the original folder even after redirection. It does not happen every time and I can not reproduce it on my machine. I suspect it is some kind of cache problem.

The MEF loading code looks like this:

using (var catalog = new AggregateCatalog()) {

    Console.WriteLine("Loading components from {0}", folder);

    catalog.Catalogs.Add(new DirectoryCatalog(folder, "*.dll"));

    using (var container = new CompositionContainer(catalog)) {
        try {
            container.ComposeParts(this);
        }
        catch (ReflectionTypeLoadException ex) {
            foreach (var loaderException in ex.LoaderExceptions) {
               // log loading error
    }
}

foreach (var assembly in _allComponents.GroupBy(x => x.GetType().Assembly)) {
    Console.WriteLine("Loaded from {0}", assembly.Key.CodeBase);
}

The result from the code above looks like

Loading components from C:\NewPlugins
Loaded from C:\OldPlugins

Solution

  • Since, according to your comment, you are having in both directories assemblies with the same identity, the output from your code above, is normal. This is not an issue with DirectoryCatalog. It does load try to load an assembly from the specific directory but the CLR will not load it if an assembly with the same identity is are already loaded in the current AppDomain. It doesn't matter from where the assembly was loaded, all it matters is the identity.

    The solution is to make your assemblies strong named and increment the version whenever you create an update to a plugin. This way the assemblies in the NewPlugins directory will have a different identity from the ones already loaded from OldPlugins directory.

    If you are interested in learning how assemblies are loaded have a look at Suzanne Cook's blog entries on assembly loading.