I am trying to release a shared instance or singleton value. Does anyone know how to do this? Do I have to refresh the catalog? I'm learning MEF so please help.
Example of class
[Export]
public class Foo
{
public RandomProperty {get;set;}
[ImportConstructor]
public Foo() {}
}
You can create it with something like this:
var fooSingleton = ServiceLocator.GetInstance(typeof(Foo));
All fine and good, but ideally I would like to do something like this
Container.Replace(oldFoo, newFoo);
So when I call it again
var fooSingleton = ServiceLocator.GetInstance(typeof(Foo));
fooSingleton will have the new value.
I think the answer probably relies in actually clearing out the catalog and then refreshing it - but this seem overkill for such a simple thing.
By default in MEF, when you create an Export, is is shared. In many other containers, this is referred to as the Singleton lifestyle. This means that releasing the export will do nothing, since the container needs to hang on to the export for other potential consumers.
You really have 2 options in front of you:
[PartCreationPolicy (CreationPolicy.NonShared)]
. This will cause the Dispose
method to be called on your parts when container.ReleaseExport(myExport)
is called where myExport
is an export (not an exported value) that is kept around to releasing purposes.Here is an example:
var catalog = new AggregateCatalog(// code elided);
var container = new CompositionContainer(catalog);
Lazy<IMyExportInterface> myExport = container.GetExport<IMyExportInterface>();
// later on...
container.ReleaseExport(myExport)
This shows that you need to do this where you have access to the MEF container, and where you have kept a reference to the export.
Caution, however. Changing to transient objects instead of singletons will affect the performance of the container as reflection is used to create each new object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With