views:

60

answers:

1

I have coded a service like that :

public interface IMyInterface
{
  ...
}

[Export(typeof(IMyInterface))]
internal class MyService : IMyInterface
{
  ...
}

Now, I'd like to import several instances of MyService with MEF in my main program.

How can I do that ?

With [Import] private IMyInterface MyService { get; set; } I only get 1 instance of MyService. In my main program, I'd like to dynamically specify the number of imported instance of MyService before MEF composition.

I don't want to use [ImportMany] because I don't want to specify the number of export in my MyService implementation.

Can you help me ?

+1  A: 

You probably don't want to do this as straight imports, but get the exported value from the container several times. Because of this, you need to change the creation policy to NonShared, which forces the container to instantiate a new instance each time.

[Export(typeof(IMyInterface)) PartCreationPolicy(CreationPolicy.NonShared)]
internal class MyService : IMyInterface
{
  ...
}

Then get the value from the container:

List<IMyInterface> instances = new List<IMyInterface>();
for (int i = 0; i < 10; i++) {
  instances.Add(container.GetExportedValue<IMyInterface>());
}
Matthew Abbott
Thank you, it is exactly what I needed ;-).
Patrice Pezillier
@Patrice It would usually be better to use an ExportFactory<IMyInterface> instead of calling into the container multiple times. See this answer: http://stackoverflow.com/questions/3285469/loading-plugins-at-runtime-with-mef/3286167#3286167
Daniel Plaisted