[英]How to import several instances with MEF?
我编写了这样的服务:
public interface IMyInterface
{
...
}
[Export(typeof(IMyInterface))]
internal class MyService : IMyInterface
{
...
}
现在,我想在我的主程序中使用MEF导入MyService
几个实例。
我怎样才能做到这一点 ?
使用[Import] private IMyInterface MyService { get; set; }
[Import] private IMyInterface MyService { get; set; }
[Import] private IMyInterface MyService { get; set; }
我只得到1例MyService
。 在我的主程序中,我想在MEF组合之前动态指定MyService
的导入实例的数量。
我不想使用[ImportMany]
因为我不想在MyService
实现中指定导出数。
你能帮助我吗 ?
您可能不希望以直接导入方式执行此操作,而是多次从容器中获取导出值。 因此,您需要将创建策略更改为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>());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.