How to release a shared instance from an MEF container

I am trying to release a generic instance or singleton value. Does anyone know how to do this? Do I need to update the catalog? I am studying MEF, so please help.

Class example

[Export]
public class Foo
{
  public RandomProperty {get;set;}

  [ImportConstructor]
  public Foo() {}
}

You can create it something like this:

var fooSingleton = ServiceLocator.GetInstance(typeof(Foo));

Everything is fine and good, but ideally I would like to do something like this

Container.Replace(oldFoo, newFoo);

So when will I call him again

var fooSingleton = ServiceLocator.GetInstance(typeof(Foo));

fooSingleton will have a new meaning.

I think the answer probably relies on actually clearing the directory and then updating it - but that seems redundant for such a simple thing.

+5
source share
2 answers

MEF . . , , .

2 :

  • , , . , , .
  • , , . MEF, PartCreationPolicy Export , . : [PartCreationPolicy (CreationPolicy.NonShared)]. Dispose , container.ReleaseExport(myExport) , myExport - ( ), .

:

var catalog = new AggregateCatalog(// code elided);
var container = new CompositionContainer(catalog);

Lazy<IMyExportInterface> myExport = container.GetExport<IMyExportInterface>();
// later on...
container.ReleaseExport(myExport)

, , MEF, .

, . , .

+3

Shared, . , , .

var export = container.GetExport<Foo>();
container.ReleaseExport(export);

, , ( Import), .

0