给定一个带有 [Import] 标签的任意已经存在的对象,为了让 MEF 填充导入,我必须做什么手鼓舞?
许多博客文档似乎是针对 MEF 的预览版构建的,并且不再有效 - 我使用的是作为 .NET 4.0(或者 MEF 2.0 Preview 3)一部分的已发布文档。
AggregateCatalog _catalog;
CompositionContainer _container;
public void Composify(object existingObjectWithImportTags)
{
lock(_container) {
var batch = new CompositionBatch();
// What do I do now?!?!
}
}
最佳答案
MEF 解析导入(通过属性或构造函数注入(inject)),连同它们自己的依赖项,从目录中注册的已注册程序集中的导出类型(包括当前程序集) ).
如果你想直接创建一个对象(使用 new
关键字),或者如果 export 在创建时还没有准备好,你可以使用容器满足对象的导入,使用:
_container.SatisfyImportsOnce(yourObject);
我已经整理了一个小场景来执行此操作。这是代码:
public class Demo
{
private readonly CompositionContainer _container;
[Import]
public IInterface Dependency { get; set; }
public Demo(CompositionContainer container)
{
_container = container;
}
public void Test()
{
//no exported value, so the next line would cause an excaption
//var value=_container.GetExportedValue<IInterface>();
var myClass = new MyClass(_container);
//exporting the needed dependency
myClass.Export();
_container.SatisfyImportsOnce(this);
//now you can retrieve the type safely since it's been "exported"
var newValue = _container.GetExportedValue<IInterface>();
}
}
public interface IInterface
{
string Name { get; set; }
}
[Export(typeof(IInterface))]
public class MyClass:IInterface
{
private readonly CompositionContainer _container;
public MyClass()
{
}
public MyClass(CompositionContainer container)
{
_container = container;
}
#region Implementation of IInterface
public string Name { get; set; }
public void Export()
{
_container.ComposeExportedValue<IInterface>(new MyClass());
}
#endregion
}
现在,只需使用 new Tests(new CompositionContainer()).Test();
开始演示。
希望这有帮助:)
关于c# - 使用 MEF 满足现有对象的导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5544788/