I will try to describe it as simple as possible. We have SqlConnection and 3 methods.
1st type
This type open one SqlConnection and methods’ have property SqlConnection. Basically they just use sConnection and within method the create, use, close SqlCommand and SqlDataReader
using (SqlConnection sConnection = new SqlConnection(string))
{
sConnection.Open();
Method objMethod = new Method();
objMethod.SqlConnection = sConnection;
objMethod.DoSomething();
Method2 objMethod = new Method2();
objMethod2.SqlConnection = sConnection;
objMethod2.DoSomething();
Method3 objMethod = new Method3();
objMethod3.SqlConnection = sConnection;
objMethod3.DoSomething();
}
2nd type
This type will create new SqlConnection, SqlCommand, SqlDataReader within every method separately. For 3 methods it will have to Open and Close 3 SqlConnections.
Method objMethod = new Method();
objMethod.DoSomething();
Method2 objMethod = new Method2();
objMethod2.DoSomething();
Method3 objMethod = new Method3();
objMethod3.DoSomething();
Question is whether to keep SqlConnection encapsulated within methods or is it safe to create on SqlConnection and use that opened connection within methods without need to open new.
Thanks
Sql Connections are pooled so if you are concerned with performance; chances are that both methods will use just one connection and therefore, the penalty for using the second approach is negligible.
On the other hand, the second approach shows better encapsulation and separation of concerns. I would go with the second option.