1

I am using MEF as an IOC in my application. I found myself stuck in a situation where I need exactly two instance at a time for a class in my application (across all threads). I thought it would be easy just by adding export attribute twice with different container name and then using that container name to create two instances.

[Export("Condition-1",typeof(MyClass)]
[Export("Condition-2",typeof(MyClass)]
[PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.Shared)]
public class MyClass  {   }

And then export them as

Container.GetExport<MyClass>("Condition-1").Value
Container.GetExport<MyClass>("Condition-2").Value

But this trick did not work. I finally able to solve my problem by using CompsositionBatch

cb.AddExportedValue<MyClass>("Condition-1",new MyClass());
cb.AddExportedValue<MyClass>("Condition-2",new MyClass());

But my question is, Why am I not able to get different instances on the basis of Contract Name. Is it right that Contract name does not matter if CreationPolicy is shared?

ZafarYousafi
  • 8,640
  • 5
  • 33
  • 39

1 Answers1

0

The problem is in the setup of PartCreationPolicyAttribute that decorates MyClass.

CreationPolicy.Shared means that a single instance will be returned for each call to Container.GetExport. It is like a singleton. What you need in your case is the CreationPolicy.NonShared policy which will return a different instance for each clla to Container.GetExport.

Here's a good article on Part Creation Policy. Also have a look at ExportFactory in MEF 2 for MEF2 additions regarding the lifetime and sharing of parts

Panos Rontogiannis
  • 4,154
  • 1
  • 24
  • 29
  • I don't want NonShared. I want semi shared. Means I want a shared instance if imported with contract name "Condition-1" and another shared instance if imported with contract name "Condition-2". I want a shared instance attached to contract name and not to class type. Thats why I was decorating the class with two export attributes. – ZafarYousafi Mar 26 '13 at 11:26