I'm using dapper-dot-net for data access in my ASP.NET MVC
application.
So in order to supply a connection string
I've came up with the following pattern:
public static class ConnectionStringManager
{
private static readonly SqlConnection conn;
static ConnectionStringManager()
{
//initialize the connection with value from web.config file
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnName"].ConnectionString);
}
public static SqlConnection GetOpenConnection()
{
if (conn.State != System.Data.ConnectionState.Open)
conn.Open();
return conn;
}
}
And a sample use of it with in a query:
public Customer GetCustomerById(int id)
{
string sql = @"select * from Customer where Id = @id";
using (var conn = ConnectionStringManager.GetOpenConnection())
{
Customer cust = conn.Query<Customer>(sql, new { id }).FirstOrDefault();
return cust;
}
}
So my question is if this is a good approach or not, and if not, what would you suggest to do different?