【发布时间】:2023-03-09 13:39:01
【问题描述】:
我正在尝试使用 Microsoft.Practices.ServiceLocation.ServiceLocator 和 MEF。接口 IServiceLocator 使用两个参数定义方法 GetInstance。第一个参数是 serviceType,第二个参数是 key。
我有两个实现接口 IMyInterface 的类,它们具有 Export 属性:[Export(typeof(IMyInterface)), PartCreationPolicy(CreationPolicy.Shared)]
public class Class1 : IMyInterface
{}
[Export(typeof(IMyInterface)), PartCreationPolicy(CreationPolicy.Shared)]
public class Class2: IMyInterface
{}
我想通过 Prism ServiceLocator GetInstance 方法获取 Class1 的实例:
ServiceLocator.Current.GetInstance(typeof(IMyInterface),"Key");
但我不知道应该如何以及在哪里定义“关键”。我试图在导出属性中定义键:
[Export("Key1",typeof(IMyInterface)), PartCreationPolicy(CreationPolicy.Shared)]
public class Class1 : IMyInterface
{}
[Export("Key2",typeof(IMyInterface)), PartCreationPolicy(CreationPolicy.Shared)]
public class Class2: IMyInterface
{}
当我使用 key 参数调用方法 GetInstance 时
ServiceLocator.Current.GetInstance(typeof(IMyInterface),"Key1");
我得到 Microsoft.Practices.ServiceLocation.ActivationException(尝试获取 IMyInterface 类型的实例时发生激活错误,键“Key1”)。有人知道如何定义导出密钥吗? 谢谢
【问题讨论】: