I have an sqlConnection manager class like so:
public class SQLConn {
public string connStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
private SqlConnection sqlConn;
public SqlConnection Connection()
{
sqlConn = new SqlConnection(connStr);
return sqlConn;
}
public void Open()
{
sqlConn .Open();
}
}
If I use a function with the 'using' statement like:
var conn = new SQLConn();
using (conn.Connection())
{
String query = "Select * from table";
objSql = new SqlCommand(query, conn.Connection());
conn.Open();
DoSomething();
}
Does the using statement dispose of the connection automatically since conn.Connection()
returns a SqlConnection object? Or, do I have to implement IDisposable and a custom Dispose method on the SqlConn class?
Is this even a good way at all? I'm working with legacy code and I'm not able to use an ORM yet but is there a way to simplify this existing pattern to manage/create SQL connections?
The using
statement will look at the final type of the expression - i.e. whatever is returned from .Connection()
; if this returns something that is IDisposable
, then you're OK.
The compiler will tell you if you get it wrong ;-p (it won't let you use using
on something that isn't IDisposable
).
You should probably watch out for where you are creating two connections:
using (var c = conn.Connection()) // <==edit
{
String query = "Select * from table";
objSql = new SqlCommand(query, c); // <==edit
c.Open();
DoSomething();
}
and possibly:
public SqlConnection Connection()
{
if(sqlConn == null) sqlConn = new SqlConnection(connStr); // <== edit
return sqlConn;
}
It will work but after the using {}
you will be left with an sqlConn that internally holds a Disposed SqlConnection. Not a really useful situation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With