Import property always null (MEF import issue)

前端 未结 2 775
庸人自扰
庸人自扰 2021-02-04 01:53

I try for some time to get things done using MEF but now, I run into a problem i need help.

Description: I have 2 DLL and one EXE file. ClassLibrary1 (LoggerImpl.cs, Som

2条回答
  •  -上瘾入骨i
    2021-02-04 02:10

    If you create a new instance of a class yourself (new SomeClass()), the container won't know anything about it and won't compose it.

    For a part to be composed by MEF, it needs to be created by MEF, or passed explicitly to the container. You can manually tell MEF to satisfy the SomeClass object's imports in the same way you told it to satisfy the form's imports:

    SomeClass c = new SomeClass();
    _container.SatisfyImports(c);
    c.Print();
    

    However, you need direct access to the container to do this, so it doesn't work as well outside of your Form1 class. In general, a better way to do it would be to export SomeClass, and create an import in your Form1 class for SomeClass:

    [Export]
    public class SomeClass
    {
        [Import("Logging", typeof(ILogger))]
        public ILogger Log { get; set; }
    
        // etc.
    }
    
    public partial class Form1 : Form
    {
        [Import("Logging", typeof(ILogger))]
        public ILogger Log { set; get; }
    
        [Import]
        SomeClass _someClass { get; set; }
    
        // etc.
    }
    

提交回复
热议问题