MEF allows two types of exports - shared and non-shared.
Shared exports are like singletons - every consumer shares the same instance. These shared instances are directly managed by MEF. When you call Dispose() on the MEF container, it automatically releases these objects in the reverse order of import.
Non-shared resources are more complicated. Because there are multiple instances, MEF does not guarantee a proper order of release. In this case, you should follow the same guidelines as those used for calling Dispose() to determine when to release an imported object.
Each non-shared MEF-imported object should have an owner responsible for its lifecycle - usually the parent object which imported it in the first place. Once the parent object has ensured that no one is using this imported object, it would call ReleaseExport on it. The typical pattern is to release the imported object in the Dispose() of the owner object.
class OwnerClass : IDisposable
{
[Import(RequiredCreationPolicy=CreationPolicy.NonShared)]
private ConsumedClass myInstance;
[Import(RequiredCreationPolicy=CreationPolicy.Shared)]
private CompositionContainer container;
// Do stuff
public void Dispose()
{
container.ReleaseExport(myInstance);
{
}
Calling ReleaseExport releases that specific instance from the container. The definition remains in the catalog. So you should still be able to create more instances. Here's a nice discussion:
https://mef.codeplex.com/discussions/228535
The job of ReleaseExport is to cleanup a particular export and it's dependencies from the container early, meaning before disposing of the container itself which will cleanup and dispose all objects constructed by the container. Now calling ReleaseExport will do different things depending on the particular export, for example for a Shared export it will actually do nothing but for a NonShared export it will release it and walk its dependency graph releasing them but again it will stop and do nothing for any dependencies that are Shared exports.