Is this the right way to dispose the SQLConnection

前端 未结 3 1643
盖世英雄少女心
盖世英雄少女心 2021-01-11 13:17

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

3条回答
  •  悲哀的现实
    2021-01-11 13:41

    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.

提交回复
热议问题