gpt4 book ai didi

c# - EventAggregator 和 ServiceLocator 问题

转载 作者:行者123 更新时间:2023-11-30 21:05:18 24 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

要么您使用 Prism(是吗?)并且您需要正确设置您的 Bootstrap - 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。然后,您应该创建自定义 Bootstrap 、注册您的类型并运行 Bootstrap 。

public class CustomBootstrapper : UnityBootstrapper 
{
}

并调用

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

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

关于c# - EventAggregator 和 ServiceLocator 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11765435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com