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