EventAggregator and ServiceLocator Issue

℡╲_俬逩灬. 提交于 2019-12-08 01:44:44

问题


I started working on a WPF project using Prism and MVVM, and I am trying to use the eventAggregator but, when the line below is executed an exception is raised:

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

But I cant understand what I am doing wrong, maybe this is a very simple thing, but I have been struggling with this for a couple hours.

Hope someone can help me, thanks in advance


回答1:


You lack the initialization code of your locator.

Either you use Prism (do you?) and you need to set up your bootstrapper correctly - http://msdn.microsoft.com/en-us/library/gg430868(PandP.40).aspx

Or you don't use Prism and you just set up the locator manually (in Main for example):

IUnityContainer container = new UnityContainer();

// register the singleton of your event aggregator
container.RegisterType<IEventAggregator, EventAggregator>( new ContainerControlledLifetimeManager() ); 

ServiceLocator.SetLocatorProvider( () => container );

then you can call in any place of your code

var eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();

Edit: you have edited your question and you now mention Prism. You should then create a custom bootstrapper, register your types and run the bootstrapper.

public class CustomBootstrapper : UnityBootstrapper 
{
}

and call

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

in the starting routine of your application. From what I remember, UnityBootstrapper registers the IEventAggregator as singleton so you don't have to repeat that.



来源:https://stackoverflow.com/questions/11765435/eventaggregator-and-servicelocator-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!