在 Prism 的不同模块中订阅事件

Subscribing to an event in a different module in Prism

在我的 LoginModule 视图模型中,我正在调度一个事件:

void LoginUpdate(object sender, EventArgs e)
{
    _eventAggregator.GetEvent<LoginStatusEvent>().Publish(_status);
}

EventModule中:

public class LoginStatusEvent : PubSubEvent<LoginStatus>
{
}

然后我尝试在不同的模块中订阅它:

public class EventModule : IModule
{
    IRegionManager _regionManager;
    IEventAggregator _eventAggregator;
    private SubscriptionToken subscriptionToken;
    private bool isLoggedIn { get; set; }

    public EventModule(IEventAggregator eventAggregator, IRegionManager regionManager)
    {
        _regionManager = regionManager;
        _eventAggregator = eventAggregator;

        LoginEventsListener();
    }

    public void Initialize()
    {

    }

    public void LoginEventsListener()
    {
        LoginStatusEvent loginStatusEvent = _eventAggregator.GetEvent<LoginStatusEvent>();

        if (subscriptionToken != null)
        {
            loginStatusEvent.Unsubscribe(subscriptionToken);
        }

        subscriptionToken = loginStatusEvent.Subscribe(LoginStatusEventHandler, ThreadOption.UIThread, false);
    }

    public void LoginStatusEventHandler(LoginStatus loginStatus)
    {
        Trace.WriteLine(">> Got it!!");

    }

}

但是 LoginStatusEventHandler 从未触发,我也没有收到任何错误。

OP 在订阅事件时没有保留 Subscriber Reference,所以在一瞬间 class 根本没有引用并被 GC 收集。

所以在这种情况下,它将使用 True 标志进入 Subscribe 方法。

正如@Haukinger 所说:

在 Prism 文档中 https://github.com/PrismLibrary/Prism/blob/ef1a2266905a4aa3e7087955e9f7b5a7d71972fb/Documentation/WPF/30-ModularApplicationDevelopment.md#initializing-modules

Module instance lifetime is short-lived by default. After the Initialize method is called during the loading process, the reference to the module instance is released. If you do not establish a strong reference chain to the module instance, it will be garbage collected. This behavior may be problematic to debug if you subscribe to events that hold a weak reference to your module, because your module just "disappears" when the garbage collector runs.