MEF如何导入多个实例?

3
我编写了一个类似这样的服务:

我已经编写了一个这样的服务:

public interface IMyInterface
{
  ...
}

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

现在,我想在我的主程序中使用MEF导入多个MyService实例。请问如何操作?
通过[Import] private IMyInterface MyService { get; set; }只能获取1个MyService实例。在我的主程序中,我想在MEF组合之前动态指定导入的MyService实例数量。
我不想使用[ImportMany],因为我不想在MyService实现中指定导出的数量。
你能帮我吗?
1个回答

6

你可能不想直接导入这些内容,而是从容器中多次获取导出值。因此,您需要将创建策略更改为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>());
}

2
@Patrice,通常最好使用ExportFactory<IMyInterface>而不是多次调用容器。请参阅此答案:http://stackoverflow.com/questions/3285469/loading-plugins-at-runtime-with-mef/3286167#3286167 - Daniel Plaisted

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接