MEF: Though Shalt Not LoadFrom

I was preparing for a presentation on MEF, and I stumbled upon this sentence:

catalog.Catalogs.Add(new DirectoryCatalog("C:\\SimpleCalculator\\SimpleCalculator\\Extensions"));

This absolute path is for debugging purposes only. In a production application, you would use a relative path.

The article does not explain why it is so, but I sensed it has to do with LoadFrom context. Basically, when you load an assembly via absolute path outside of your application directory, it gets placed in a special context that is a source of all kinds of trouble.

For a moment I hoped that MEF invented some kind of cure for this disease. In DirectoryCatalog they create an AssemblyCatalog for each file found in the directory, and AssemblyCatalog does this:

var assemblyName = AssemblyName.GetAssemblyName(filePath);

Voila? Jackpot? An override of Assembly.Load() that takes an absolute path, albeit in a cloaked form!

Not so fast, folks. Although this is called Assembly.Load(), it will still use LoadForm context if the path is outside of the application directory. This can be confirmed by writing a small example and enabling LoadFromContext debug assistant in Visual Studio (Debug→xceptions→Managed Debuggin Assistants).

The bottom line: MEF’s DirectoryCatalog, as well as Assembly.Load(AssemblyName) will still use LoadFrom context if the path is outside of the application base. This is exactly why one should use relative paths for DirectoryCatalog.

Leave a Reply

Your email address will not be published. Required fields are marked *