Bug and workaround in dotnet MEF — The export is not assignable to type .

Today, while writing an app use netfx 4.8 with MEF support based on System.ComponentModel.Composition 4.5 from nuget, a strange bug hit me.

Because I’m not treat MEF as essential, I’d like to write the main code in a project and create MEF wrap in another one like:

  • In Project A: class Real : InterfaceA
  • In Project B: class MEFWrap : Real, and marked with Export attribute.

Certainly, Project A is referenced by Project B.  While building the solution, both dlls generated from Project A and Project B are placed in the output folder of Project B.

While trying to use MEF to load the class from Project B, the funny thing happened:

  • If AssemblyCatalog is chosen to create the object, from the assembly object loaded by LoadFrom method, nothing is wrong, but
  • If AggregateCatalog is used with all assemblies loaded from the folder (Project A and Project B) at the same time, an exception raised while calling ComposesParts:

    The export InterfaceA is not assignable to type InterfaceA.

I don’t know why it’s happened but here are 2 ways to get avoid of it.

  • Only load assembly Project B, not both of them, if it’s possible, when you know the name or name pattern while searching files, or
  • Using AssemblyCatalog for each file, instead of using AggregateCatalog as a whole, will also works.

 

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.