views:

75

answers:

2

I am missing something basic when it comes to using MEF. I got it working using samples and a simple console app where everything is in the same assembly. Then I put some imports and exports in a separate project which contains various entities. I want to use these entities in an MS Test, but the composition is never actually done. When I move the composition stuff into the constructor of an entity in question it works, but that's obviously wrong. Does GetExecutingAssembly only "see" the test process? What am I missing re containers? I tried putting the container in a Using in the test without luck. The MEF docs are still very scant and I can't find a simple example of an application (or MS Test) which uses entities from a different project...

+2  A: 

Yes. You need to make sure to add your assembly (the one with imports and exports) to the catalog prior to composition. This way, it can find the appropriate parts.

GetExecutingAssembly does exactly what it says - it gets the assembly that's currently executing, which means the one that has that specific code written. In your case, this is the test assembly, not your "library" project.

Have your test add the library project to the catalog explicitly, and it will most likely work as you expect.

Reed Copsey
+2  A: 

In .NET, each exe or DLL file is called an assembly1. So when you build a catalog based on the "executing assembly" and use it at the application entry point, then you only include parts which are defined within the exe project. You don't get any parts defined in the DLLs.

Try replacing this:

var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

by this:

var catalog = new AggregateCatalog(
    new ComposablePartCatalog[]
    {
        new AssemblyCatalog(Assembly.GetExecutingAssembly()),
        new DirectoryCatalog(".")
    });

edit: I just discovered that there is a simpler solution:

var catalog = new DirectoryCatalog(".", "*");

(1) Actually, an assembly can consist of multiple files but this is rarely used. The term is also used for side-by-side COM.

Wim Coenen