Disposing of SQL Connection

本秂侑毒 提交于 2019-12-05 19:32:16
Yuck

Your design encourages hanging on to a (presumably open) SqlConnection for long periods of time. Best practice is to open a connection just before you need it and then release (close and dispose) it as soon as you are finished.

Yes, there is some overhead associated with creating new connections; connection pooling alleviates much of that processing time. Worse is keeping many connections alive on the server.

Looking at the source for the Enterprise Library (from the MS Patterns & Practices team), the DAAB creates a connection as needed and disposes it as quickly as possible.

public virtual int ExecuteNonQuery(DbCommand command)
{
    using (var wrapper = GetOpenConnection())
    {
        PrepareCommand(command, wrapper.Connection);
        return DoExecuteNonQuery(command);
    }
}

protected DatabaseConnectionWrapper GetOpenConnection()
{
    DatabaseConnectionWrapper connection = TransactionScopeConnections.GetConnection(this);
    return connection ?? GetWrappedConnection();
}

So I would say that is a best practice. In most cases, all you are doing is returning the connection to the connection pool, so really the connection is not closed per se.

yamen

If you wish to wrap the SQL Connection class, implement IDisposable and call the connection Dispose() from within your own Dispose() method. More info is here:

Properly disposing of a DbConnection

As to whether or not this is good practice - well, if all your doing is wrapped the SQL connection in another class, I'm not sure what you're achieving. All your methods will still need access to the instance of this class, in which case they could get access to the instance of the connection object by itself.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!