簡體   English   中英

Prism事件聚合器不能從單獨的模塊工作

[英]Prism event aggregator not working from separate module

我遇到了棱鏡事件聚合器的問題。 如果我訂閱,並在同一模塊中發布一個事件,它工作正常。 像這樣 -

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);
    }
}

但是,如果我在另一個模塊中訂閱該事件,則在調用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");
    }
}

基礎架構模塊首先注冊,因此問題不在於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));
    }
}

根據OP的注釋,對象被實例化,然后被銷毀。
這使得Publish("OtherModule"); 代碼什么都不做,因為監聽器被破壞了。

確實,如果你將KeepSubscriberReferenceAlive設置為true
它將起作用,因為您的EventAggregator將保留對訂閱者對象( InfrastructureModule )的引用。
這並不理想,基本上你使用的是弱事件模式,你不會冒內存泄漏的風險,
必須處理對象的生命周期,從而冒着內存泄漏的風險,就像常規的.NET事件一樣。

不要誤會我的意思,我不是說你絕對不應該使用KeepSubscriberReferenceAlive,但它應該只在極少數情況下使用。

話雖如此,您的測試用例是一個奇怪的場景:Bootstrapper將在您定義的每個模塊上調用Initialize,然后您的shell不會保存這些模塊。 由於沒有人擁有這些模塊,它們就被摧毀了。

Initialize的“正常”用法是將正在初始化的模塊注入Shell (或任何其他UserControl),這是有道理的:你不想初始化你不會使用的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM