Trying to track down some memory leaks in our WPF/MVVM app and something occurred to me...
If you listen to ModelItem events in its associated ViewModel with an instance-specific handler, doesn’t that make the ViewModelItem hang around as long as the ModelItem still exists?
Consider this case...
public class ItemViewModel
{
public ItemViewModel(ModelItem item)
{
this.Item = item;
item.SomeEvent += ItemSomeEventHandler
}
Public ModelItem Item{ get; private set; }
// Note: This is a handler on this instance, not a shared handler
Private void ItemSomeEventHandler(object s, EventArgs e)
{
Console.WriteLine(“The model changed!”);
}
}
If this does cause a leak, how/where do you unhook it? You can't do it in 'Dispose' since that won't be called if something still has a reference to it, which it looks like it does: the model item.
Would the proper place be to implement Dispose in the control where this ViewModel is used, then trickle down an event-unhook routine there? Seems a bit treacherous to rely on something external to make sure you clean up your own internal, but short of going to an EventManager architecture, I'm not sure what to do here.