EventAggregator和ServiceLocator问题

我开始使用Prism和MVVM开发一个WPF项目,我正在尝试使用eventAggregator但是,当执行下面的行时会引发exception:

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

但是我无法理解我做错了什么,也许这是一件非常简单的事情,但我已经在努力了几个小时。

希望有人可以帮助我,提前谢谢

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

要么你使用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( new ContainerControlledLifetimeManager() ); ServiceLocator.SetLocatorProvider( () => container ); 

然后你可以在代码的任何地方打电话

 var eventAggregator = ServiceLocator.Current.GetInstance(); 

编辑:您已编辑过您的问题,现在提到Prism。 然后,您应该创建一个自定义引导程序,注册您的类型并运行引导程序。

 public class CustomBootstrapper : UnityBootstrapper { } 

并打电话

 var bootstrapper = new CustomBootstrapper(); bootstrapper.Run(); 

在您的应用程序的启动例程中。 根据我的记忆, UnityBootstrapperUnityBootstrapper注册为单例,因此您不必重复这一点。