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
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