使用MEF满足现有对象的导入

时间:2011-04-04 21:54:06

标签: c# mef

鉴于任意已存在的对象归属于[导入]标签,为了让MEF填写进口,我必须做什么手鼓舞?

许多博客文档似乎是针对MEF的预览版本而构建的,并且不再起作用了 - 我正在使用已发布的.NET 4.0(或者MEF 2.0预览版3)。

AggregateCatalog _catalog;
CompositionContainer _container;

public void Composify(object existingObjectWithImportTags)
{
    lock(_container) {
        var batch = new CompositionBatch();

        // What do I do now?!?!
    }
}

2 个答案:

答案 0 :(得分:7)

MEF从目录中注册的已注册程序集中的导出类型(包括当前程序集)解析 Imports (通过属性或构造函数注入)及其自身的依赖项)。

如果您想直接创建对象(使用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();即可开始演示。

希望这会有所帮助:)

答案 1 :(得分:3)

_container.ComposeParts(existingObjectWithImportTags);

ComposeParts是您正在寻找的扩展方法。

它只是创建一个CompositionBatch并调用AddPart(AttributedModelServices.CreatePart(attributesObject)),然后调用_container.Compose(batch)。