我有一个导入对象无法正常工作,它是空的。最初它是一个 ImportMany,但我将其简化为 Import 以尝试确定问题所在,但是我并没有成功。
我已经查阅了这个网站和谷歌,并遵循了主要思路:
- 不要自己实例化类,让 MEF 来处理它,否则调用 container.getExport() - 仍然无法工作 - 在包含 [Import] 属性的类上放置 [Export],否则容器组合过程不会将其识别为部件(在调试时确认)。
我的代码设置如下(为了简洁起见而简化): Assembly1
我已经查阅了这个网站和谷歌,并遵循了主要思路:
- 不要自己实例化类,让 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
}
}
汇编语言2
public interface IMyComponent
{
//stuff...
}
Assembly3
[Export(typeof(IMyComponent)]
public MyComponent : IMyComponent
{
//more stuff...
}
有人知道或者有想法为什么MEF容器没有注入XLHandler中的_component变量吗?
我需要在Assembly2中导出/创建一个AssemblyCatalog接口吗?
[Import(typeof(IMycomponent))]
,对吗? - p.s.w.gIMyComponent
,所以你也必须按此导入。你可以从导入中删除typeof
定义,因为你的变量类型已经是 IMyComponent。 - ChrisO