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

标签 c# mef

给定一个带有 [Import] 标签的任意已经存在的对象,为了让 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?!?!
    }
}

最佳答案

MEF 解析导入(通过属性或构造函数注入(inject)),连同它们自己的依赖项,从目录中注册的已注册程序集中的导出类型(包括当前程序集) ).

如果你想直接创建一个对象(使用 new 关键字),或者如果 export 在创建时还没有准备好,你可以使用容器满足对象的导入,使用:

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

希望这有帮助:)

关于c# - 使用 MEF 满足现有对象的导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5544788/

相关文章:

c# - 检查列表是否包含多个指定值

c# - 解耦 View 、表示和 ASP.NET Web 窗体

c# - 具有多个构造函数的 MEF 构造函数参数

C# 在任何窗口上查找选定的控件

javascript - 使用 JINT 从 javascript 文件读取 JSON 对象

c# - ASP.Net 如何从 gridview C# 更新数据库

c# - UINib 的 Xamarin DequeueReusableCell 始终生成 null

.net - MEF 保留 NonShared IDisposable 部分的引用,不允许 GC 收集它们

c# - 如何使用 Rhino Mocks 模拟 MEF 导出?

configuration - MEF 插件有自己的配置文件吗?