Search code examples
c#memory-leaksmefcomposition

How to unregister a ComposablePart from CompositionContainer


I am using MEF with a static CompositionContainer. My classes use this container like this:

public void SomeClass
{
    [Import(typeof(AnotherClass)]
    private AnotherClass Instance {get;set;}

    public SomeClass()
    {
        MEFContext.RegisterAttributedPart(this); // this basically calls CompositionContainer.ComposeParts(this);
    }
}

The problem now is, that the Instance of SomeClass will never be released because the CompositionContainer keeps an instance to it. How would i be able to release this instance?

Additional informations:

  • AnotherClass has a PartCreationPolicy with CreationPolicy.Shared

Solution

  • In .NET 4 it seems that the used implementation of MEF does not support child containers and filtered catalogs. I solved the problem above by creating a new container and use a catalog which only contains the necessary items. This container is disposed when I do not need it anymore. In .NET 4.5 this could be solved with child containers.