我正在尝试使用Microsoft.Practices.ServiceLocation.ServiceLocator和MEF。接口IServiceLocator定义了具有两个参数的GetInstance方法。第一个参数是serviceType,第二个参数是key。
[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");
但是我不知道“key”应该在哪里定义。我尝试在导出属性中定义key:
[Export("Key1",typeof(IMyInterface)), PartCreationPolicy(CreationPolicy.Shared)]
public class Class1 : IMyInterface
{}
[Export("Key2",typeof(IMyInterface)), PartCreationPolicy(CreationPolicy.Shared)]
public class Class2: IMyInterface
{}
当我使用关键参数调用GetInstance方法时。
ServiceLocator.Current.GetInstance(typeof(IMyInterface),"Key1");
我遇到了Microsoft.Practices.ServiceLocation.ActivationException错误(尝试获取类型为IMyInterface,关键字为“Key1”的实例时发生激活错误)。请问有人知道如何定义导出关键字吗?
[ImportMany(typeof(IMyInterface))]
只会导入那些没有契约名称导出的部件。 - Adi Lester