鉴于任意已存在的对象归属于[导入]标签,为了让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?!?!
}
}
Run Code Online (Sandbox Code Playgroud)
MEF 根据目录中注册的已注册程序集中的导出类型(包括当前程序集)解析Imports(通过属性或构造函数注入)及其自身的依赖项.
如果要直接创建对象(使用new关键字),或者在创建时导出尚未就绪,则可以使用容器来满足对象的导入,使用:
_container.SatisfyImportsOnce(yourObject);
Run Code Online (Sandbox Code Playgroud)
我做了一个小场景就是这么做的.这是代码:
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
}
Run Code Online (Sandbox Code Playgroud)
现在,只需使用new Tests(new CompositionContainer()).Test();即可开始演示.
希望这可以帮助 :)