Search code examples
.netclass-designidisposable

Design dilemma: who should handle disposable parameter?


If my class uses disposable resource in it's constructor (DbConnection if it matters) should I implement IDisposable in my class and dispose DbConnection object, or let user handle disposal of DbConnection?

Currently I implement IDisposable in my class, but now I see some possible negative effects: clutters class design, double disposal of DbConnection if used incorrectly. But there are also positive ones: simplier use is the major one (especially if you use multiple disposable parameters).

In the "wild" I see both approaches, so I can't decide..

Update: Thanks everyone for answers, which, in fact, showed that it's indeed not an simple choice sometimes. And it's hard to pick correct answer too. However I decided to stick to most simple one to follow in future. So final choice is: do not implement IDisposable.


Solution

  • It should be disposed by whoever created it - the same scope as its creation. You create an object, you're responsible for disposing it. Simple as that.