I am a winform guy moving to asp.net mvc and all my methods are opening and closing connection (shortLived)
public void Save()
{
using (var conn=new SqlConnection(ConnectionString))
{
conn.Open()
et.....
}
}
but I have noticed that you tend to keep the connection open and having a class to handle the connectivity implementing IDisposible and then keep this connection open.something like
public class DbManager : IDisposable
{
private IDbConnection Conn { get; set; }
public IDbConnection Connection
{
get
{
if (Conn.State == ConnectionState.Closed)
Conn.Open();
return Conn;
}
}
public DbManager(string connString)
{
Conn = new SqlConnection(connString);
}
public void Dispose()
{
if (Conn == null) return;
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
Conn.Dispose();
}
Conn = null;
My understanding was that it's not the responsability of the consumer to close connectivity and also I am not sure whether you would run out of pools if you have many requests
can somebody clarify what is the best practice?
Please note that I am not using EF but pure ado.net,just in case you mention dbcontext etc...
It seems all wrong to me ,Am I missing the obvious
thanks for clarifying
FYI
I am implementing my own aspnet identity provider (NO EF) and noticed that people do the following in the web project which seems wrong to me as you coupling your datalayer to your UI:
Shall I just shut my brain and follow?
app.CreatePerOwinContext(ApplicationDbContext.Create);
public class ApplicationDbContext : DbManager
{
public ApplicationDbContext(string connectionName)
: base(connectionName)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
}
}