我正在尝试使用Microsoft.Practices.ServiceLocation.ServiceLocator和MEF。接口IServiceLocator定义带有两个参数的方法GetInstance。第一个参数是serviceType,第二个参数是关键。
我有两个实现接口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
{}


当我用关键参数调用方法GetInstance时

ServiceLocator.Current.GetInstance(typeof(IMyInterface),"Key1");


我收到Microsoft.Practices.ServiceLocation.ActivationException(尝试获取IMyInterface类型的实例,键为“ Key1”的实例时发生激活错误)。有人知道如何定义导出密钥吗?
谢谢

最佳答案

Prism使用MefServiceLocatorAdapter使MEF的CompositionsContainer适应IServiceLocator界面。这是它用来获取帮助的实际代码:

protected override object DoGetInstance(Type serviceType, string key)
{
    IEnumerable<Lazy<object, object>> exports = this.compositionContainer.GetExports(serviceType, null, key);
    if ((exports != null) && (exports.Count() > 0))
    {
        // If there is more than one value, this will throw an InvalidOperationException,
        // which will be wrapped by the base class as an ActivationException.
        return exports.Single().Value;
    }

    throw new ActivationException(
        this.FormatActivationExceptionMessage(new CompositionException("Export not found"), serviceType, key));
}


如您所见,您正在正确导出并调用GetInstance。但是,我相信您的服务定位器设置不正确,这就是为什么您遇到此异常的原因。如果您使用Prism的MefBootstrapper初始化应用程序,则应该已经为您完成了。否则,您将需要使用以下代码对其进行初始化:

IServiceLocator serviceLocator = new MefServiceLocatorAdapter(myCompositionContainer);
ServiceLocator.SetLocatorProvider(() => serviceLocator);

关于c# - Prism ServiceLocator GetInstance和MEF,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24697859/

10-10 02:50