在Microsoft.Practices.ServiceLocation.dll中发生错误“Microsoft.Practices.ServiceLocation.ActivationException” [英] getting error 'Microsoft.Practices.ServiceLocation.ActivationException' occurred in Microsoft.Practices.ServiceLocation.dll

查看:1969
本文介绍了在Microsoft.Practices.ServiceLocation.dll中发生错误“Microsoft.Practices.ServiceLocation.ActivationException”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是单元测试基于MVVM的应用程序,使用棱镜和使用模拟测试视图模型。我可以通过传递区域管理器和资源管理器的模拟对象调用我的viewmodel类的构造函数,但是当控制在构造函数内时,它失败在以下语句:

  private EventAggregator()
{
this.eventAggregatorInstance = ServiceLocator.Current.GetInstance< IEventAggregator>();
}它给出错误:Microsoft.Practices.ServiceLocation.dll中出现类型为Microsoft.Practices.ServiceLocation.ActivationException的未处理异常

其他信息:尝试获取类型IEventAggregator,键的实例时发生激活错误。请帮助解决这个问题。

解决方案

我看到你通过添加EventAggregator到你的容器解决了你的问题。

但是,我建议您的ViewModel不应该使用ServiceLocator 来解析EventAggregator。 ServiceLocator是一个美化的静态实例,基本上是反模式(请参阅服务定位器是反模式)。您的ViewModel应该最有可能通过依赖注入在构造函数中接受EventAggregator,并从中使用它。我不认为你应该需要一个容器来测试你的ViewModel。你可以使用它们的构造函数构造它们,并传递它们的依赖对象的任何模拟实现(作为构造函数的参数)。


I am Unit Testing MVVM based application that uses prism and using mocking to test view model . I am able to call the constructor of my viewmodel class by passing mock objects of region manager and resource manager but when control goes inside constructor it fails at the following statement :

private EventAggregator()
        {
            this.eventAggregatorInstance = ServiceLocator.Current.GetInstance<IEventAggregator>();
        }                                                                                 It gives error : An unhandled exception of type 'Microsoft.Practices.ServiceLocation.ActivationException' occurred in Microsoft.Practices.ServiceLocation.dll

Additional information: Activation error occured while trying to get instance of type IEventAggregator, key "". Please help how to resolve this.

解决方案

I see you solved your problem by adding the EventAggregator to your container.

However, I would suggest that your ViewModel should not be using the ServiceLocator to resolve the EventAggregator at all. The ServiceLocator is a glorified static instance that is basically an anti-pattern (see Service Locator is an Anti-Pattern). Your ViewModel should most likely accept the EventAggregator in the constructor via dependency injection and use it from there. I don't think you should need a container to test your ViewModels. You could just construct them with their constructors and pass them any mock implementations of their dependent objects (as parameters to the constructor).

这篇关于在Microsoft.Practices.ServiceLocation.dll中发生错误“Microsoft.Practices.ServiceLocation.ActivationException”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆