I am maintaining code that was written by another developer. I came across this in a rather large class (assume 20 or 30 functions--I show only 3 below):
public class Widget
{
DisposableObject do = new DisposableObject();
private void function1()
{
do.something();
...
}
private void function2()
{
do.something();
...
}
private void function3()
{
do.something();
...
}
}
For my question, what 's important to consider the following:
- DisposableObject implements IDisposable and therefore can be used with the C# using statement.
- do is a class-global object that's being used by more than one function within the class. Assume for the sake of discussion that I cannot easily determine if one function does something with the do object that changes its state and then calls another function within the class. Also, no function within the class passes do as an argument--they all tap into the class-global instance.
- I have detected that object do holds a connection to a database because some of these functions are buggy and the object isn't getting disposed of properly.
Ideally, I want to somehow refactor this class so that I can do something like this:
using (DisposableObject do = new DisposableObject())
{ ... }
Unfortunately, I don't know enough about how the do object is changing among this classes various functions--otherwise I could just remove the global declaration and add using statements to each function.
Is there a neat way to use, say, dependency injection or perhaps a factory to ensure that this class continues to function in its dysfunctional way yet would properly dispose of object do when the code that consumes this class is finished doing what it needed to do? I want to ensure that do is properly disposed of but I also want to be sure that I don't break the existing code.
Thank you for your help.