2011-04-04 175 views
6

滿足現有對象的導入由於[Import]標籤賦予了任意已有的對象,爲了讓MEF填充導入,我必須做什麼鈴鼓舞?使用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?!?! 
    } 
} 
+0

如果您知道如何在第一次嘗試時拼出手鼓 – toddmo 2013-12-17 17:06:19

回答

6

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();開始演示。

希望這有助於:)

+0

不,這不起作用,SatisfyImportsOnce需要一個ComposablePart - 這是我的核心問題。 – 2011-04-04 23:03:24

+0

有一個重載(或更確切地說是一個擴展方法),它可以使任何對象滿足其導入。我嘗試了我放在這裏的確切示例,它工作得很好;) – AbdouMoumen 2011-04-04 23:16:39

+0

啊,你需要一個「使用System.ComponentModel.Composition」語句(不只是.Hosting) - 感謝提示! – 2011-04-06 00:22:48

3
_container.ComposeParts(existingObjectWithImportTags); 

ComposeParts是,你正在尋找一個擴展方法。

它只是創建一個CompositionBatch並調用AddPart(AttributedModelServices.CreatePart(屬性對象)),然後調用_container.Compose(batch)。