我如何获得MEF容器进行自我注射 [英] How do i get MEF container to inject himself

查看:94
本文介绍了我如何获得MEF容器进行自我注射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将构造函数注入与MEF组成容器一起使用,我想知道如何使CompositionContainer自己将其注入到他提供的对象的实例上.

I'm using constructor injection with MEF Composition Container and I want to know how can I make the CompositionContainer inject itself on the instance of the object he is providing.

推荐答案

您可以使用

You can use one of the CompositionContainer.ComposeExportedValue methods to create a part from a given object.

这里是一个示例:

class Program
{
    static void Main(string[] args)
    {
        var container = new CompositionContainer(new ApplicationCatalog());
        Console.WriteLine("Main: container [{0}]", container.GetHashCode());

        container.ComposeExportedValue<CompositionContainer>(container);

        var exp = container.GetExportedValue<ExportThatNeedsContainer>();

        Console.ReadKey();
    }
}

[Export]
public class ExportThatNeedsContainer
{
    [ImportingConstructor]
    public ExportThatNeedsContainer(CompositionContainer cc)
    {
        Console.WriteLine("ExportThatNeedsContainer: cc [{0}]", cc.GetHashCode());
    }
}

这可行,但是据我所知,将容器注入零件并不是MEF的正常"用例.

This works, however injecting the container to a part, as far as I know, is not a "normal" use-case of MEF.

这篇关于我如何获得MEF容器进行自我注射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆