SqlConnection Connection Disposed

Hi all,

I have class library which provides a custom type called SqlServerAccessor
This custom type wraps a SqlConnection and its ctor accepts a connection string, news up a SqlConnection, and calls _connection.Open().
This type implements IDisposable and is intended to be used as follows:

try
{
    using var sql = new SqlServerAccessor(connectionString);
    DataTable result = sql.ExecuteQuery(...);
    // Do something with the result
}
catch (Exception ex)
{
    // Sql connection failed
}


Internally, I have a method called EnsureNotDisposed() to handle use after the type has been disposed which throws an InvalidOperationException stating the underlying SqlConnection has been disposed.
Using the code sample from above, this catch is always hit and the sql connection is always closed. There does not seem to be a "keep alive" function or anything - my understanding is that SqlConnection should keep its connection open until it is manually closed.

I could connect and disconnect for each operation, which might resolve the issue, but the intent is for it to be used in a small using scope like this and calling Dispose() or Close() is responsible for closing the connection.

Any idea why the connection is being closed immediately after leaving the ctor?
Was this page helpful?