This project has moved and is read-only. For the latest updates, please go here.

ComposeExportedValue And GetExport - Need new instance everytime

Nov 1, 2010 at 12:23 PM

Since I have multi threaded application, I need to get new instance of composed part every time.

I have one class called ClassA Which is being composed in RegisterComponents class as under:

public class ClassA : IClassA
// Some logic goes here...

public class RegisterComponents
public VitalsModule(CompositionContainer container)
this.container = container;

public void RegisterServices()
this.Container.ComposeExportedValue<IClassA>(new ClassA());


Now I am getting instance of ClassA into another class ClassB which is being called by multiple threads. I want new instance of
ClassA every time I get it from CompositionContainer.

public void ClassB
// this way i m getting lazy export
var lazyInstance = CompositionContainerHost.CompositionContainer.GetExport<IClassA>();

// Now i m creating instance of this export
// Here i need new instance every time...
var instance = lazyInstance.Value; //
 But here I am not getting new instance every time and ClassA constructor will not get called every time.

Thanks in Advance.
Nov 7, 2010 at 8:41 AM

Instead of adding ClassA to the container via ComposeExportedValue simply export ClassA and mark it as a non-shared part like:

public class ClassA : IClassA  

Nov 8, 2010 at 6:25 AM

Yes, by declaring Export on ClassA... I was able to solve my issue..
but what I wanted to know is "there is any way to get new instance using ComposeExportedValue" or is it limitation of MEF???


Nov 8, 2010 at 5:06 PM

ComposeExportedValue is literally adding an object instance into the container it is not registering a type can can be created multiple times. PartCreationPolicy is only used by our CatalogExportProvider when it create an instance from a Catalog. In order to get what you want in MEF's default implementation ClassA would need to be in a Catalog.

Unlike other DI containers MEF doesn't have a default mechanism to register types manually, MEF works by discovering the types via Catalogs.

Nov 9, 2010 at 4:21 AM

Thanks for the info.
This is what I understand so far... I think there are only two ways to get new instance from Container.
1. Using CreationPolicy on Export attribute.
2. Using ExportFactory

Let me know if any other way out there to get new instance using ComposeExportedValue method.