Prism event aggregator does not work from a separate module

I'm having problems with the prism event aggregator. If I subscribe and post an event in the same module, it works fine. Like this -

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

However, if I subscribe to an event in another module, nothing happens when eventAggregator.GetEvent (). Called Publish () -

 public class OtherModule : IModule { private IEventAggregator eventAggregator; public OtherModule (IEventAggregator eventAggregator) { this.eventAggregator = eventAggregator; } public void Initialize() { eventAggregator.GetEvent<TestEvent>().Publish("Other module"); } } 

The Infrastructure module is registered first, so the problem is not that the OtherModule is posting the event before there is a subscriber. Any ideas what is going wrong?

Edit: Here I register the modules

 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)); } } 
+6
source share
1 answer

Based on OP comments, objects are created and then destroyed right after.
This is done by Publish("OtherModule"); do nothing because the listener has been destroyed.

Now really, if you set KeepSubscriberReferenceAlive to true ,
it will work because your EventAggregator will keep a reference to the subscribing object ( InfrastructureModule ).
This is not ideal, basically you switched from using a weak event pattern in which you do not risk memory leaks, to be able to work with objects of life and, therefore, to risk memory leaks, like a regular .NET event.

Don't get me wrong, I'm not saying that you should absolutely not use KeepSubscriberReferenceAlive, but it should be used only in rare cases.

At the same time, your test script is an odd script: Bootstrapper is called Initialize on each module you define, and then your shell does not support these modules. Since no one holds these Modules, they are destroyed.

The โ€œnormalโ€ use for Initialize is to introduce a module that is initialized in Shell (or any other UserControl), and it makes sense: you do not want to initialize what you will not use.

+8
source

Source: https://habr.com/ru/post/904610/


All Articles