This project has moved. For the latest updates, please go here.
All versions of MEF implement some level of tracking of the parts that the composition engine creates. In MEF for Windows Store apps (System.Composition namespaces) this is for the purpose of ensuring that disposable parts can be released properly.

To avoid holding on to part instances for longer than is required, the following guidance applies.

Where multiple instances of a part need to be created, use an ExportFactory<T> rather than calling GetExports() multiple times on the container.

This code may leak memory.

// Within the class declaration of a part
CompositionContext _container = ...;


// If page objects have disposable dependencies,
// they will be tracked by _container.
public Page CreatePage()
{
    _container.GetExport<Page>();
}

Creating a page: this code does not leak.

// Within the class declaration of a part

[Import]
public ExportFactory<Page> PageFactory { get; set; }

public Page CreatePage()
{
   return PageFactory.CreateExport().Value;
}

If the Export<T> instance is garbage collected, all collectible parts will also be free for collection (regardless of whether or not Dispose() is called).

The Export<T> instance returned from the CreateExport() method can be disposed in order to dispose related parts:

public void ShowPage()
{
   using (var page = PageFactory.CreateExport())
   {
      // Outside the using block, the page and its dependencies
      // will be disposed.
      page.Value.Show();
   }
}

If you need to use CompositionContext (rather than ExportFactory<T>) for some reason, e.g. to implement a service locator, then use ExportFactory<CompositionContext> to create a new CompositionContext for each unit of work.

This applies when using CompositionContext.SatisfyImports() as well.

Last edited Oct 18, 2012 at 7:29 PM by alokshriram, version 1

Comments

No comments yet.