How do i get MEF container to inject himself

早过忘川 提交于 2020-01-05 10:33:25

问题


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.


回答1:


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

Here's a sample:

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());
    }
}

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




回答2:


I'm not sure it could work. Imagine you have a container with three classes, one of them also contains the container itself, which contains the three classes. It would be a stackoverflow :)



来源:https://stackoverflow.com/questions/19960069/how-do-i-get-mef-container-to-inject-himself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!