How to import multiple instances using MEF?

I encoded this service:

public interface IMyInterface
{
  ...
}

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

Now I would like to import multiple instances MyServiceusing MEF in my main program.

How can i do this?

Since [Import] private IMyInterface MyService { get; set; }I get only 1 instance MyService. In my main program, I would like to dynamically indicate the number of imported instances MyServicebefore the MEF composition.

I do not want to use [ImportMany], because I do not want to indicate the amount of export in my implementation MyService.

Can you help me?

+3
source share
1 answer

, , . - NonShared, .

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

:

List<IMyInterface> instances = new List<IMyInterface>();
for (int i = 0; i < 10; i++) {
  instances.Add(container.GetExportedValue<IMyInterface>());
}
+6

Source: https://habr.com/ru/post/1755477/


All Articles