Search code examples
c#prismmef

MEF and Import to interfaces?


I'm using Prism with MEF Extensions and am having some trouble with project setup regarding an import to an interface. The problem is that the interface doesn't live in the same assembly as the concrete implementation (because there are other concrete implementations in other projects as well using the same interface).

So because I only have a reference to the project with the interface, and the concrete implementation is never directly referenced in my main app, it never gets included in the bin directory. So at run time MEF composition fails because its trying to inject a class for which there is no assembly containing the implementation.

What is the right way to do this? I could always copy it to the bin dir, but that sucks... or I could copy it to a plugin directory, but that sucks too, because the other concrete implementations would have to live in that same plugins directory.

Either I'm totally missing something, or this is not a good use for MEF, or ...?


Solution

  • MEF implementation modules generally are not referenced by the main project - the whole point of MEF is to be able to load different stuff at runtime.

    I create a post-build action in the main project in VS to copy the MEF modules to whatever the main project is expecting to find MEF modules in - either bin, or a subdir of bin.

    You could instead change the build output directory in each of the MEF module projects to output the module binaries to the main project bin dir or subdir of bin.

    I'm not familiar with Prism, but with plain old MEF with .NET 4.0 I construct a MEF catalog of the MEF module file paths, usually from info found in the main project's config file. (Loading all dlls found in a directory is an invitation for trouble)

    Even though the main project doesn't reference the MEF modules, you can still get VS to build the MEF modules when you build the main project, by adding the MEF modules to the Project Dependencies of the main project. Make sure all the MEF module projects are included in the same solution as the main project. Right click on the main project in the Solution Explorer, select Project Dependencies, and put a check mark next to all the MEF modules. This will also cause the main project to be recompiled when the MEF modules change, which isn't strictly necessary but still a good idea in case you change an interface somewhere.