Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MEF doesn't find parts in other assemblies

Tags:

.net

mef

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...

like image 796
Steve Macdonald Avatar asked Mar 26 '10 20:03

Steve Macdonald


2 Answers

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.

like image 199
Wim Coenen Avatar answered Nov 08 '22 04:11

Wim Coenen


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.

like image 26
Reed Copsey Avatar answered Nov 08 '22 03:11

Reed Copsey