I've got a Window, which gets a viewmodel instance injected into its constructor.
The window sets its
DataContext to that viewmodel.
The viewmodel contains a command to "submit" the window and a command to "cancel" the window.
The commands are attached to buttons in the window (via a Binding expression in XAML).
The viewmodel also contains two events:
The events are invoked whenever the corresponding command of the viewmodel is executed.
I use events on the viewmodel to be able to know from within the window's codebehind if a command was executed on the viewmodel. The window should set its
DialogResult, and should
Close() itself whenever the viewmodel's submit/cancel command is executed.
The window is always shown using
The viewmodel instance that is passed into the window constructor, has a lifetime equal to the total lifetime of the application. So, the viewmodel lifetime is longer than the lifetime of the window. While the window itself will go out of scope and will be created again multiple times. So, what happens:
- Window is created, viewmodel is put into constructor
- Window subscribes to viewmodel events.
- Viewmodel command is executed.
- Viewmodel invokes an event.
- Window reacts to viewmodel event and closes itself (and
- The window goes out of scope.
When above process is executed multiple times, the window instances are actually not garbage collected, because they subscribed to the (longer living) viewmodel events, and internally events keep a reference to their subscribers. This is actually a well-known memory leak mistake in C#.
But I don't know how to solve this issue.
I was thinking to implement the
IDisposable interface on the window, and unsubscrive from the events in the
Dispose method. But some sources say this is not a good idea.
Using a destructor (finalizer) on the window doesn't seem to be a good solution either.
What would be best practise?