Provide different values for same Import using MEF

May 26, 2011 at 4:42 PM

I want to provide different values for the same import in these two scenarios

[Export("A1", typeof(IA))]
[Export("A2", typeof(IA))]
class A : IA
{
  [Import("B")]
  public IB B;
}

[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(IA))]
class A : IA
{
  [Import]
  public IB B;
}

In both of the two scenarios above, I want to satisfy the import of IB with different values that is when I do this in the first type of export

var a1 = Container.GetExportedValue<IA>("A1");
var a2 = Container.GetExportedValue<IA>("A1");

or this in the second export

var a1 = Container.GetExportedValue<IA>();
var a2 = Container.GetExportedValue<IA>();

I want the two instance of A a1 and a2 to have different values of IB. I don't want to use ImportMany because then I have to decide which one to choose and I want to keep that logic out of class A.

The two scenarios related to these exports are that I want to have a common generic view to work with different types of view models implementing some interface and different instances of a class that provides some service to be configured with different configuration parameters.

May 27, 2011 at 8:32 AM
Edited May 27, 2011 at 10:23 AM

Since you cross-posted to stackoverflow, I've answered over there.