© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•15mo ago•
12 replies
TheBrambleShark

SqlConnection Connection Disposed

Hi all,

I have class library which provides a custom type called
SqlServerAccessor
SqlServerAccessor

This custom type wraps a
SqlConnection
SqlConnection
and its ctor accepts a connection string, news up a
SqlConnection
SqlConnection
, and calls
_connection.Open()
_connection.Open()
.
This type implements
IDisposable
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
}
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()
EnsureNotDisposed()
to handle use after the type has been disposed which throws an
InvalidOperationException
InvalidOperationException
stating the underlying
SqlConnection
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
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()
Dispose()
or
Close()
Close()
is responsible for closing the connection.

Any idea why the connection is being closed immediately after leaving the ctor?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Creating a SqlConnection connection via connection string
C#CC# / help
3y ago
SqlConnection not defined?
C#CC# / help
3y ago
❔ Connection Timeout argument passed doesn't work for a SqlConnection
C#CC# / help
3y ago
TcpClient being Disposed
C#CC# / help
2y ago