How do i get MEF container to inject himself

2019-07-31 14:42发布

问题:

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 :)