Search code examples
c#disposedbconnection

Properly disposing of a DbConnection


I have a class called DatabaseHelper that wraps a DbConnection. What's the proper way to setup this class for a using statement? I have implemented IDisposible, but I'm not sure when and where I should be calling Connection.Close() or Connection.Dispose().

When I simply call Connection.Dispose() in my own Dispose() method, I'll sometimes get a SocketException from my DbConnection object. I assume this is because old connections are being left open, but there's no details attached the to exception, so I can't know for sure.


Solution

  • Call connection.Dispose() from within your dispose method. You should look at the standard pattern for implementing IDisposable, which goes above and beyond simply implementing the IDisposable interface and allows for disposing unmanaged objects etc:

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    
    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                // Dispose managed resources.
            }
    
            // There are no unmanaged resources to release, but
            // if we add them, they need to be released here.
        }
        disposed = true;
    
        // If it is available, make the call to the
        // base class's Dispose(Boolean) method
        base.Dispose(disposing);
    }
    

    (Taken from http://msdn.microsoft.com/en-us/library/system.idisposable.aspx).