Disposing of Objects with long living dependencies
- by Ray Booysen
public class ABC
{
public ABC(IEventableInstance dependency)
{
dependency.ANewEvent += MyEventHandler;
}
private void MyEventHandler(object sender, EventArgs e)
{
//Do Stuff
}
}
Let us say that an instance of ABC is a long living object and that my dependency is an even longer running object. When an instance of ABC needs to be cleaned up, I have two options.
One I could have a Cleanup() method to unsubscribe from the ANewEvent event or I could implement IDisposable and in the Dispose unwire the event. Now I have no control over whether the consumer will call the dispose method or even the Cleanup method should I go that route.
Should I implement a Finaliser and unsubscribe then? It feels dirty but I do not want hanging instances of ABC around.
Thoughts?