I was wondering if my below implementation is the most efficient way to dispose the SQLconnection in this case.
I know normally if i\'m using the SqlConnection dire
Assuming IRepository
inherits from IDisposable
, your implementation is fine provided you are not keeping an instance of your SqlRepository
class open for longer than it takes to perform a 'logical' sequence of queries on the database. The fact that this sequence might span several method calls is not a problem.
I disagree with @bryanmac's answer:
Don't keep the connection open spanning calls. You're defeating connection pooling.
Provided your sequence of method calls belong together, and you don't keep the connection open for longer than it takes to complete the logical sequence, I don't see how this in any way defeats connection pooling.
One comment though. You should:
Either implement the standard IDisposable
pattern (with a protected void Dispose(bool disposing)
method that can be overridden in derived classes
Or make your class sealed, in which case your existing IDisposable
implementation is fine.