A couple months ago, I encountered an issue in which I have to perform some cleanup on one of my ViewModel. I know that there's an OnExit() function on the Application class, but I didn't know how to let my VM know from here without causing some tight coupling between the Application class and my VM (which is not ideal).
I gave up trying to solve it since I couldn't found a viable solution back then, and always put this bug aside. Today I decided to spend the day fixing this issue, and I did, with a lot of help from the internet.
The solution was to use the EventAggregator in the PRISM 5 library
1. Make a singleton which contain the EventAggregator
I gave up trying to solve it since I couldn't found a viable solution back then, and always put this bug aside. Today I decided to spend the day fixing this issue, and I did, with a lot of help from the internet.
The solution was to use the EventAggregator in the PRISM 5 library
1. Make a singleton which contain the EventAggregator
// singleton event system public static class EventSystem { public static IEventAggregator Instance { get { // ?? operator, return left if not null, otherwise, return right return m_Instance ?? (m_Instance = new EventAggregator()); } } private static IEventAggregator m_Instance; }
2. Create the Event to be broadcasted
public class ApplicationExitEvent : PubSubEvent<int> { }
3. Make my VM subscribe to the event
token = EventSystem.Instance.GetEvent<ApplicationExitEvent>().Subscribe( OnApplicationExit, ThreadOption.PublisherThread );
The ThreadOption CANNOT be UIThread, I guess since the UI is closed there's no more UI Thread.
The token is used to unsubscribe from the event (not shown)
The token is used to unsubscribe from the event (not shown)
4. Broadcast the event from Application.OnExit
protected override void OnExit(ExitEventArgs e) { // broadcast that we're exiting EventSystem.Instance.GetEvent<ApplicationExitEvent>().Publish(e.ApplicationExitCode); }
I wonder if I would've solved this issue a lot sooner if I know about EventAggregator beforehand (I didnt know about it before I found someone else's blog trying to solve the same issue)
Links that helped me:
Links that helped me: