Search code examples
c#mef

MEF Import not working for me, but container works as expected


I have the following very structure: I have a host class, which creates the catalogs and containers and uses [ImportMany] to import a class from a dll in a directory. The catalog and container both include the correct class, but the enumerable I try to fill with ImportMany stays empty. I compared my problem to 10+ similar cases, but none of the solutions I found helped me. What am I overlooking?

Here is the HostClass, it simply gets instantiated from Program.Main() and DoStuff() is called.

public class HostClass
{ 
    private CompositionContainer _container;

    [ImportMany]
    public IEnumerable<Lazy<IOperation, IOperationData>> operations;

    public HostClass()
    {
        var catalog = new AggregateCatalog();
        catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
        catalog.Catalogs.Add(new DirectoryCatalog(@"Path/to/Folder"));

        _container = new CompositionContainer(catalog);

        CompositionBatch batch = new CompositionBatch(); // Found as answer to a similar problem, but did not help in my case
        batch.AddExportedValue(this._container);

        try
        {
            this._container.Compose(batch);
            this._container.ComposeParts(this);
            this._container.SatisfyImportsOnce(this);  // // Found as answer to a similar problem, but did not help in my case
        }
        catch (CompositionException compositionException)
        {
            Console.WriteLine(compositionException.ToString());
        }
    }

    public void DoStuff()
    { // Stuff with operations}

The class that should be exported:

[Export(typeof(IOperation))]
[ExportMetadata("Type", "myType")]
class Operation: IOperation
{ // Stuff }

Both the Host namespace and the namespace of the exported dll contain their own interface IOperation, but when I played around with Microsoft own MEF tutorial, this didn't seem to be a problem. To avoid any problems in that regard, I did try to use Import/Export("Teststring") on both sides, which did not help either. Furthermore, when I compare it step by step in the debugger with the MS tutorial adjusted to my structure, the only difference is, that the enumeration gets filled after this._container.ComposeParts(this); in the tutorial, while it turns empty (but not null, at least) in my actual application

Thanks!


Solution

  • Solved it by using a separate assembly for the common interfaces.

    The error seems indeed to be in some hiccups in the example projects I used to compare the behavior, even if they have no references between host and export to the best of my knowledge - I simply noticed the behavior doesn't reproduce, after moving all classes from example to my application by hand.