interface IMyInterace
{
void Open();
object Read();
void Close();
}
class MyImplementation : IMyInterface
{
public void Open() { /* instantiates disposible class */ }
//...
public void Close() { /* calls .Dispose(); */ }
}
Is there a good way to deal with this type of situation to ensure that disposible instances inside the class get called? (There is no signal to callers that they must call ‘Close’ except in documentation.) Implementations of IMyInterface do not necessarily encapsulate IDisposible instances and are closed and reopened repeatedly throughout the application’s lifetime.
I’m thinking of doing this:
- Implement IDisposible in MyImplementation.
- Set Dispose() to call Close().
- Add a call to Close() or Dispose() to the
begining of Open to ensure previous
call was closed.
Users of IMyInterface do not know what implementation they are using, so I’m not sure how much value making MyImplementation disposible has, and again, not all implementations will encapsulate IDisposibles.
In addition to the answers already here:
If this class is (often/sometimes) used through the interface alone I would advice to inherit IMyInterace from IDisposable.
That will let your users use these objects in a consistent manner. The drawback is of course that you may need to add (dummy) Dispose methods to classes that don’t actually need it. But the benefit is in consistency and flexibility: What if a class changes in the future so that it does need a Dispose() ?
A minimal approach: