Search code examples
c#mef

mefx does not list an importer


I have a MEF-based modular app that has started to fail to import classes. In the course of debugging, I've been using the mefx tools to try to track down the core issue. In short, all of my [Export] declarations appear to be correct, but none of the Import or ImportMany attributes seem to be processed correctly.

Hopefully this is a simple mistake on my part, but the application was working until recently.

Here is a very short test application I've written along with the corresponding mefx output.

using System.ComponentModel.Composition;

namespace ClassLibrary1
{
    public class Class1
    {
        [Import]
        public Class2 myclass;
    }

    [Export]
    public class Class2
    {
    }
}

And the mexf output

> mefx /file:ClassLibrary1.dll /parts
ClassLibrary1.Class2

> mefx /file:ClassLibrary1.dll /exports
ClassLibrary1.Class2

> mefx /file:ClassLibrary1.dll /imports
[blank]

I would have expected Class1 to be listed as an importer. Suggestions?


Solution

  • You cannot import in a class not referenced by MEF.

    Try:

    namespace ClassLibrary1
    {
        [Export]
        public class Class1
        {
            [Import]
            public Class2 myclass;
        }
    
        [Export]
        public class Class2
        {
        }
    }
    

    You could also import it in the constructor:

    namespace ClassLibrary1
        {
            [Export]
            public class Class1
            {
                [ImportingConstructor]
                public Class1(Class2 c2)
                {
                    myclass = c2;
                }
    
                public Class2 myclass;
            }
    
            [Export]
            public class Class2
            {
            }
        }
    

    Also, use the ServiceLocator to get Class1 (don't use the "new" keyword).

    Class1 myClass1 = ServiceLocator.Current.GetExport<Class1>();