EventAggregator and ServiceLocator Issue

本文关键字:Issue ServiceLocator and EventAggregator | 更新日期: 2024-09-21 03:31:55

我开始使用Prism和MVVM处理WPF项目,并尝试使用eventAggregator,但当执行下面的行时,会引发异常:

IServiceLocator ob = ServiceLocator.Current; // This line causes a Null pointer exception
EventAggregator = ob.GetInstance<IEventAggregator>();

但我不明白我做错了什么,也许这是一件很简单的事情,但我已经为此挣扎了几个小时。

希望有人能帮助我,提前感谢

EventAggregator and ServiceLocator Issue

您缺少定位器的初始化代码。

要么你使用Prism(是吗?),你需要正确设置引导程序-http://msdn.microsoft.com/en-us/library/gg430868(PandP.40).aspx

或者您不使用Prism,只需手动设置定位器(例如在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();

在应用程序的启动例程中。根据我的记忆,UnityBootstrapperIEventAggregator注册为singleton,所以您不必重复。