MEF解析进口(通过属性或构造注射),沿均可进行他们自己的依赖关系,从出口类型在目录中注册的注册组件(包括当前组件)。
如果您想直接创建一个对象(使用new
关键字),或在情况下,出口还没有准备好,在创作的时候,你可以用容器满足的进口对象,使用:
_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();
开始演示。
希望这有助于:)
如果您知道如何在第一次尝试时拼出手鼓 – toddmo 2013-12-17 17:06:19