Say you have 3 classes that implement IDisposable – A, B and C. Classes A and B are both dependent on class C.
-
Would it be correct to say that classes A and B’s typical implementation of Dispose() would be:
public void Dispose() { if (m_C != null) m_C.Dispose(); } -
If there’s an instance of A and and instance of B that share the same instance of C, how would you overcome the problem that disposing an instance of A would damage the instance of B?
-
Last minute addendum – If in point 2 it’s a DI container that instantiates all instances, who is responsible for disposing of the objects? Is it the container itself? How?
Thanks,
urig
The dispose pattern relies on there being a well-established “owner” who gets to decide when the resource should be disposed of.
If A and B need to refer to the same instance of C, then only one of them should act as “owner”.
While you can do what amounts to reference counting, I usually find it’s better to just document who “owns” what. For example, when you create a
Bitmapwith a stream, from that point on theBitmapowns the stream, and you shouldn’t dispose it yourself. This can cause a few issues, but it’s ultimately simpler than trying to dredge up reference counting.