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

Pat*_*ier 3 c# import mef interface

我编写了这样的服务:

public interface IMyInterface
{
  ...
}

[Export(typeof(IMyInterface))]
internal class MyService : IMyInterface
{
  ...
}
Run Code Online (Sandbox Code Playgroud)

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

我怎样才能做到这一点 ?

随着[Import] private IMyInterface MyService { get; set; }我只得到1个实例MyService.在我的主程序中,我想动态指定MyServiceMEF组合之前导入的实例数.

我不想使用,[ImportMany]因为我不想在我的MyService实现中指定导出数.

你能帮助我吗 ?

Mat*_*ott 6

您可能不希望以直接导入方式执行此操作,而是多次从容器中获取导出值.因此,您需要将创建策略更改为NonShared,这会强制容器每次实例化一个新实例.

[Export(typeof(IMyInterface)) PartCreationPolicy(CreationPolicy.NonShared)]
internal class MyService : IMyInterface
{
  ...
}
Run Code Online (Sandbox Code Playgroud)

然后从容器中获取值:

List<IMyInterface> instances = new List<IMyInterface>();
for (int i = 0; i < 10; i++) {
  instances.Add(container.GetExportedValue<IMyInterface>());
}
Run Code Online (Sandbox Code Playgroud)

  • @Patrice 通常最好使用 ExportFactory&lt;IMyInterface&gt; 而不是多次调用容器。看到这个答案:http://stackoverflow.com/questions/3285469/loading-plugins-at-runtime-with-mef/3286167#3286167 (2认同)