Details - I have a SQL Database helper in C# with a method (like below) which establishes a connection
public void EstablishConnection()
{
oConnection = oFactory.CreateConnection();
if (oConnection.State == ConnectionState.Closed)
{
oConnection.ConnectionString = StringConnection;
oConnection.Open();
oConnectionState = ConnectionState.Open;
}
}
For any calls made to db methods like (ExecuteNonQuery etc) this is how a typical method looks like
public DataSet DataAdapter(CommandType cmdType, string cmdText, Parameters[] cmdParms)
{
DbDataAdapter dda = null;
try
{
EstablishFactoryConnection();
dda = oFactory.CreateDataAdapter();
PrepareCommand(false, cmdType, cmdText, cmdParms);
dda.SelectCommand = oCommand;
DataSet ds = new DataSet();
dda.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (null != oCommand)
oCommand.Dispose();
CloseFactoryConnection();
}
}
And the CloseFactoryConnection(); method is like below
public void CloseFactoryConnection()
{
//check for an open connection
try
{
if (oConnection.State == ConnectionState.Open)
{
oConnection.Close();
oConnectionState = ConnectionState.Closed;
}
}
catch (DbException oDbErr)
{
//catch any SQL server data provider generated error messag
throw new Exception(oDbErr.Message);
}
catch (System.NullReferenceException oNullErr)
{
throw new Exception(oNullErr.Message);
}
finally
{
if (null != oConnection)
oConnection.Dispose();
}
}
Questions - I have this class (DBHelper) being used in all my repositories where the IOC container constructor injects this. The lifestyle of these instances is HttpContextLifecycle (I am using Structuremap which says this lifestyle means that the A single instance will be created for each HttpContext. Caches the instances in the HttpContext.Items collection.)
Is this the right TYPE of lifestyle for the db connection class i am using?
Should the class creating the connection/ opening it/ closing it be instantiated as a singleton? Or Per request?
What is the generally accepted lifestyle for these db connection establishing classes? I am using ado.net and there is no ORM.
Thanks