我有一个不起作用的导入 - 对象为空。最初它是一个 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
}
}
程序集2
public interface IMyComponent
{
//stuff...
}
程序集3
[Export(typeof(IMyComponent)]
public MyComponent : IMyComponent
{
//more stuff...
}
有人知道/知道为什么 XLHandler 中的 _component 变量没有被 MEF 容器注入(inject)吗?
我是否需要为 Assembly2 中的接口(interface)导出/创建一个 AssemblyCatalog?
最佳答案
导入部件时,您可以在属性上使用 [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...
}
}
关于c# - MEF 导入为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15180316/