MEF does not find parts in other assemblies

I missed something basic when it comes to using MEF. I worked with samples and a simple console application where everything is in the same assembly. Then I put some import and export in a separate project that contains various objects. I want to use these objects in an MS test, but the composition is never executed. When I move the composition material to the constructor of the object in question, it works, but this is clearly wrong. Does GetExecutingAssembly only “see” the testing process? What am I missing in containers? I tried putting the container to use in a test with no luck. MEF documents are still very scarce, and I cannot find a simple example application (or MS Test) that uses entities from another project ...

+7
mef
source share
2 answers

In .NET, every exe or DLL file is called assembly 1 . Therefore, when you create a directory based on an "executing assembly" and use it at the application entry point, you include only the parts that are defined in the exe project. You are not getting the parts defined in the DLL.

Try replacing this:

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

:

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

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

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

( 1 ) Actually, an assembly may consist of several files, but this is rarely used. This term is also used for parallel COM.

+9
source share

Yes. You must definitely add your assembly (one that has import and export) to the catalog before composition. Thus, he can find the corresponding parts.

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

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

+3
source share

All Articles