我开始在一个使用棱镜和MVVM的WPF项目中工作,我正在尝试使用eventAggregator,但是,当执行下面这行代码时,会引发异常:
IServiceLocator ob = ServiceLocator.Current; // This line causes a Null pointer exception
EventAggregator = ob.GetInstance<IEventAggregator>();但我不明白我做错了什么,也许这是一件非常简单的事情,但我已经为此挣扎了几个小时。
希望有人能帮助我,提前谢谢!
发布于 2012-08-02 02:46:01
您缺少定位器的初始化代码。
要么使用棱镜(真的吗?)并且您需要正确地设置引导程序- http://msdn.microsoft.com/en-us/library/gg430868(PandP.40).aspx
或者您不使用棱镜,而只是手动设置定位器(例如,在Main中):
IUnityContainer container = new UnityContainer();
// register the singleton of your event aggregator
container.RegisterType<IEventAggregator, EventAggregator>( new ContainerControlledLifetimeManager() );
ServiceLocator.SetLocatorProvider( () => container );然后,您可以在代码的任何位置调用
var eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();编辑:您已经编辑了您的问题,现在您提到了棱镜。然后,您应该创建自定义引导程序,注册您的类型并运行引导程序。
public class CustomBootstrapper : UnityBootstrapper
{
}并调用
var bootstrapper = new CustomBootstrapper();
bootstrapper.Run();在应用程序的启动例程中。据我所知,UnityBootstrapper将IEventAggregator注册为单例,因此您不必重复该操作。
https://stackoverflow.com/questions/11765435
复制相似问题