Disposing of ViewModels in Caliburn Micro and Cast

2019-02-17 15:09发布

I'm using Castle-Windsor as my container in a Caliburn-Micro Silverlight app. My ViewModel objects are reasonably chunky as they call WCF services and a bunch of other stuff. Therefore, when a window is closed I want to call container.Release(viewModel) so Castle can manage the whole decommission/disposal process, respecting the various lifecycles configured (as outlined in this post).

In my AppBootstrapper I have overridden GetInstance as follows:

protected override object GetInstance(Type serviceType, string key)
{
    if (string.IsNullOrEmpty(key)) return container.Resolve(serviceType);
    return container.Resolve(key, serviceType);
}

But I am struggling to come up with a clean/elegant way of calling container.Release(viewModel). There don't seem to be any hooks available for this.

What is the simplest way of releasing ViewModel objects returned from ViewModelLocator in a Caliburn Micro app?

1条回答
放荡不羁爱自由
2楼-- · 2019-02-17 15:45

The lifecycle you want for each of your VM types is going to have an impact here, so there is not really a right answer for the context you have provided.

The Screen base class of CM provides you with protected virtual void OnDeactivate(bool close); which is a good place to start. For your heavyweight VMs you should override this method, and if the VM is closing indicated by the close parameter, release any resources (WCF channels etc) that need to be disposed of, this would include disposing the resource (if IDisposable is relevant) and also disconnecting any references to it so that it can be cleaned up by the GC.

I don't use Castle so I can't help you in terms of configuring lifecycles etc. But if you follow the above, you aren't going to be holding on to anything heavy weight. I assume that with the correct lifecycle configuration, Castle will clean up any old instances that you aren't going to use again itself without an explicit call to Release.

查看更多
登录 后发表回答