【问题标题】:EventAggregator and ServiceLocator IssueEventAggregator 和 ServiceLocator 问题
【发布时间】:2012-08-01 18:36:50
【问题描述】:

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

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

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

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

【问题讨论】:

  • 这段代码在哪里执行,你使用的是哪个引导程序?例如,如果是 Unity,您可能应该使用 IUnityContainer 而不是 ServiceLocator 来解析实例。
  • 我没有使用任何引导程序,但感谢 Wiktor Zychla 我解决了我的问题

标签: c# wpf prism eventaggregator


【解决方案1】:

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

您要么使用 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>();

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

public class CustomBootstrapper : UnityBootstrapper 
{
}

然后打电话

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

在应用程序的启动例程中。据我所知,UnityBootstrapperIEventAggregator 注册为单例,因此您不必重复。

【讨论】:

  • 由于我是使用棱镜的新手,我不知道我必须初始化定位器。非常感谢!!
猜你喜欢
  • 1970-01-01
  • 2011-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 2010-12-26
  • 1970-01-01
相关资源
最近更新 更多