Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 958
Petr Abdulin Avatar asked Jun 24 '11 12:06

Petr Abdulin


1 Answers

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.

like image 91
Kieren Johnstone Avatar answered Sep 17 '22 16:09

Kieren Johnstone