Prism事件聚合器不能从单独的模块工作

Jim*_*_CS 6 c# wpf events prism

我遇到了棱镜事件聚合器的问题.如果我订阅,并在同一模块中发布一个事件,它工作正常.像这样 -

public class InfrastructureModule : IModule
{
    private IEventAggregator eventAggregator;

    public InfrastructureModule(IEventAggregator eventAggregator)
    {
        this.eventAggregator = eventAggregator;
        eventAggregator.GetEvent<TestEvent>().Subscribe(TestSub);
    }

    public void Initialize()
    {
        eventAggregator.GetEvent<TestEvent>().Publish("Infrastructure module");
    }

    private void TestSub(string s)
    {
        MessageBox.Show(s);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我在另一个模块中订阅该事件,则在调用eventAggregator.GetEvent().Publish()时没有任何反应 -

public class OtherModule : IModule
{
    private IEventAggregator eventAggregator;

    public OtherModule (IEventAggregator eventAggregator)
    {
        this.eventAggregator = eventAggregator;
    }

    public void Initialize()
    {
        eventAggregator.GetEvent<TestEvent>().Publish("Other module");
    }
}
Run Code Online (Sandbox Code Playgroud)

基础架构模块首先注册,因此问题不在于OtherModule在订户之前发布事件.任何想法都出错了?

编辑:这是我注册模块的地方

class Bootstrapper : UnityBootstrapper
{
    protected override DependencyObject CreateShell()
    {
        return new Shell();
    }

    protected override void InitializeShell()
    {
        base.InitializeShell();

        App.Current.MainWindow = (Window)this.Shell;
        App.Current.MainWindow.Show();
    }

    protected override void ConfigureModuleCatalog()
    {
        base.ConfigureModuleCatalog();

        ModuleCatalog moduleCatalog = (ModuleCatalog)this.ModuleCatalog;

        // Infrastructure module
        moduleCatalog.AddModule(typeof(Infrastructure.InfrastructureModule));


        moduleCatalog.AddModule(typeof(Other.OtherModule));
    }
}
Run Code Online (Sandbox Code Playgroud)

Lou*_*ann 8

根据OP的注释,对象被实例化,然后被销毁.
这使Publish("OtherModule");代码什么都不做,因为监听器被销毁了.

实际上,如果设置KeepSubscriberReferenceAlivetrue,
它将起作用,因为EventAggregator将保留对订阅者对象(InfrastructureModule)的引用.
这并不理想,基本上你使用的是弱事件模式,你不会冒内存泄漏的风险
,必须处理对象的生命周期,从而冒着内存泄漏的风险,就像常规的.NET事件一样.

不要误会我的意思,我不是说你绝对不应该使用KeepSubscriberReferenceAlive,但它应该只在极少数情况下使用.

话虽如此,您的测试用例是一个奇怪的场景:Bootstrapper将在您定义的每个模块上调用Initialize,然后您的shell不会保存这些模块.由于没有人拥有这些模块,它们就被摧毁了.

"正常"用法Initialize是将正在初始化的模块注入Shell(或任何其他UserControl),这是有道理的:你不想初始化你不会使用的东西.