I'm looking into getting started using MVVM Light, and I came across the "new" ICleanup interface. I was just w开发者_如何学运维ondering when would you cleanup the VM...when you navigate away from the page?
Also, I see there is a Main Cleanup in the ViewModelLocator which should cleanup all the VM's...when would this be used?
Thanks very much
Regards, Mauro
The advantage of the ICleanup
interface over the IDispose
implementation (that was previously there) is - as Laurent states it - that you can call it more frequently and without marking the VM as disposed. This means, you should call ICleanup.Cleanup
whenever you want/need to unregister the message handling for your VM. Obviously in this case you need to have a method that register all message handlers again when you need them later.
Personally, I'm more a friend of the IDispose
way of dealing with VM cleanup, especially as I are inclined to IOC containers. But, I can see Laurent's case and implementing IDisposable
calling Cleanup
on a VM is no trickery.
In general, the point in time when you dispose/cleanup a VM depends on how it is instantiated and the lifespan of the object. These decisions are governed by the desing of your application and there is no clear guidance to when you should do it. But keep in mind that it has to be done whenever you registered a message handler within your view model - in other cases it is not strictly needed.
And while talking about message handlers, don't forget to de-register them in your views as well when you have registered a message handler there (see this post). - On second thoughts, I'll put the code here to make it clear and for future reference:
In your view's constructor in the code behind file add the following code to ensure that the registered message handlers are released when the view is unloaded:
public MyView() {
this.Unloaded += (o, e) => { Messenger.Unregister(this); }
}
精彩评论