I have a base class for data access classes. This class implements IDisposable. This base class contains IDbConnection and creates it in the constructor.
public class DALBase : IDisposable
{
protected IDbConnection cn;
public DALBase()
{
cn = new MySqlConnection(connString);
}
public void Dispose()
{
if (cn != null)
{
if (cn.State != ConnectionState.Closed)
{
try
{
cn.Close();
}
catch
{
}
}
cn.Dispose();
}
}
}
The classes that inherit from this class actually access the database:
public class FooDAL : DALBase
{
public int CreateFoo()
{
IDbCommand cmd = CreateCommand("create foo with sql", cn);
Open();
int ident = int.Parse(cmd.ExecuteScalar().ToString());
Close();
cmd.Dispose();
return ident;
}
}
Classes that use FooDAL use a usage pattern to ensure that Dispose is called on FooDAL with this code:
using(FooDAL dal = new FooDAL())
{
return dal.CreateFoo();
}
My question is: does this also ensure that IDbCommand is disposed of properly, even if it is not wrapped in a usage pattern or does not try at last? What happens if an exception occurs during command execution?
It would also be better to create a connection instance in CreateFoo instead of the base class constructor for performance reasons?
.