I have a viewmodel which is subscribing to the event “NavigationCompletedEvent”. This viewmodel need to be loaded into memory without view. Code to subscribe is event is like
var navigationCompletedEvent = eventAggregator.GetEvent<NavigationCompletedEvent>();
navigationCompletedEvent.Subscribe(OnNavigationCompleted, ThreadOption.UIThread);
I have created the object of this viewmodel explicitly in Module like
// Register other view objects with DI Container (Unity)
var container = ServiceLocator.Current.GetInstance<IUnityContainer>();
container.RegisterInstance(typeof(ModuleCTaskButtonViewModel),
new ModuleCTaskButtonViewModel(), new ExternallyControlledLifetimeManager());
but when i am raising the event from some other viewmodule the subscribe method is not called.
It works fine if view is also loaded in memory. Any idea on this? How can I acheive it?
Thanks in advance.
By default, subscriptions to the Event aggregator are weak references. To keep your viewmodel alive, if no one else is referencing it, you must use the overload to the Subscribe function that takes a bool to indicate you want to use a strong reference.
Although, maybe your Unity incantations of which I am not aware will maintain the required lifetime… However, your experimental results suggest not…