-->

EventAggregator和服务定位问题(EventAggregator and Service

2019-09-20 15:02发布

我开始工作使用棱镜和MVVM一个WPF的项目,我想使用的eventAggregator但是,当执行线下则会引发异常情况:

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

但我不能明白我做错了,也许这是一个很简单的事情,但我一直在这个挣扎了几个小时。

希望有人能帮助我,在此先感谢

Answer 1:

你缺乏的定位的初始化代码。

无论你使用棱镜(你呢?),你需要正确设置你的引导程序- 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为单身,所以你不必重复。



文章来源: EventAggregator and ServiceLocator Issue