2011-04-04 176 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)。