【发布时间】:2013-03-02 22:44:31
【问题描述】:
我有一个不起作用的导入 - 对象为空。最初它是 ImportMany,但我将其简化为 Import 以尝试识别问题,但我没有成功。
我浏览了这个网站和谷歌并遵循了主要想法:
- 不要自己实例化类,让 MEF 来做,否则调用 container.getExport() - 仍然不起作用
- 在包含 [Import] 属性的类上放置 [Export],否则容器组合过程不会将其作为一部分拾取(在调试时确认)。
我的代码设置如下(为简洁起见进行了简化):
组装1
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
}
}
Assembly2
public interface IMyComponent
{
//stuff...
}
Assembly3
[Export(typeof(IMyComponent)]
public MyComponent : IMyComponent
{
//more stuff...
}
任何人都知道/知道为什么 XLHandler 中的 _component 变量没有被 MEF 容器注入?
我需要为 Assembly2 中的接口导出/创建一个 AssemblyCatalog 吗?
【问题讨论】:
-
对此不是 100% 确定,但 import 属性不应该是
[Import(typeof(IMycomponent))]? -
是的,您导出为
IMyComponent,因此您也必须以此方式导入。您可以从导入中删除typeof定义,因为您的变量类型已经是 IMyComponent。 -
是的,这是 Q 中的一个错字。我会改正的。
标签: c# dependency-injection null mef