I have created a custom WPF user control which is intended to be used by a third party. My control has a private member which is disposable, and I would like to ensure that its dispose method will always get called once the containing window/application is closed. However, UserControl is not disposable. I tried implementing the IDisposable interface and subscribing to the Unloaded event but neither get called when the host application closes. If at all possible, I don't want to rely on consumers of my control remembering to call a specific Dispose method.
public partial class MyWpfControl : UserControl
{
SomeDisposableObject x;
// where does this code go?
void Somewhere()
{
if (x != null)
{
x.Dispose();
x = null;
}
}
}
The only solution I have found so far is to subscribe to the Dispatcher's ShutdownStarted event. Is this a reasonable approach?
this.Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted;