I have inherited a web framework whereby the previous developer has opened and closed his database connections in the init/unload methods of the page life cycle. Essentially
I always make use of using block soemthing as below
using( SqlConnection)
{
}
so that it never cause any problem
if you dont want to write code for opening connection again and again create one class
public class SqlConnectionManager
{
public SqlConnection GetSqlConnectionManager()
{
//create and return connection
//SqlConnection con = new SqlConnection();
//return con;
}
}
In You class files
SqlConnection conn = null;
using (conn = (new SqlConnectionManager()).GetSqlConnectionManager())
{
//do work with connection
}
So by the above way you do not need to write code again and again and there is also no need to write code to close connection because its automatically get dispose by using block.