如何使用MEF导入多个实例?

时间:2010-07-20 09:34:12

标签: c# interface import mef

我编写了类似的服务:

public interface IMyInterface
{
  ...
}

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

现在,我想在我的主程序中导入几个MyService的MEF实例。

我该怎么做?

使用[Import] private IMyInterface MyService { get; set; }我只获得MyService的1个实例。 在我的主程序中,我想在MEF组合之前动态指定导入的MyService实例的数量。

我不想使用[ImportMany],因为我不想在MyService实施中指定导出次数。

你能帮助我吗?

1 个答案:

答案 0 :(得分: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>());
}