MEF导入为空

cli*_*cky 3 c# null dependency-injection mef

我有一个无效的导入 - 该对象为null.最初它是一个ImportMany,但我把它简化为导入以尝试识别问题,但我没有成功这样做.

我已经浏览了这个网站和谷歌,并遵循主要想法:

  • 不要自己实例化该类,让MEF这样做,否则调用container.getExport() - 仍然无法正常工作
  • 在包含[Import]属性的类上放置[Export],否则它将不会被容器组合过程选中(在调试时确认).

我的代码设置如下(为了紧凑而简化):

Assembly1

public class MyBootstrapper
{
    //Automatically called by ExcelDna library, I do not instantiate this class
    public void AutoOpen()
    {
        var ac1 = new AssemblyCatalog(typeof(XLHandler).Assembly);
        var ac2 = new AssemblyCatalog(typeof(MyComponent).Assembly);

        var agc = new AggregateCatalog();
        agc.Catalogs.Add(ac1);
        agc.Catalogs.Add(ac2);

        var cc = new CompositionContainer(agc);

        try
        {
            cc.ComposeParts(this);
        }
        catch (CompositionException exception) {}
    }
}

[Export]
public class XLHandler
{
    [Import(typeof(IMyComponent))]
    public IMyComponent _component;

    public void SomeMethod()
    {
        //try to use _component but it is null
    }
}
Run Code Online (Sandbox Code Playgroud)

Assembly2

public interface IMyComponent
{
    //stuff...
}
Run Code Online (Sandbox Code Playgroud)

Assembly3

[Export(typeof(IMyComponent)]
public MyComponent : IMyComponent
{
    //more stuff...
}
Run Code Online (Sandbox Code Playgroud)

有人知道/为什么XLHandler中的_component变量没有被MEF容器注入?

我是否需要在Assembly2中为接口导出/创建AssemblyCatalog?

Bla*_*hma 8

导入零件时,可以在[Import]属性上使用该属性,也可以将其作为构造函数的一部分请求并使用[ImportingConstructor]属性.

使用[Import]属性导入的任何部分都不会在类的构造函数中可用

所以在你的情况下,改变这样的XLHandler类:

[Export]
public class XLHandler
{
    [ImportingConstructor]
    public void SomeMethod(MyComponent component)
    {
        _component = component;
       // You can use _component, since it has already been resolved...
    }
}
Run Code Online (Sandbox Code Playgroud)