我有一个数据访问类的基类。这个类实现了IDisposable接口。这个基类包含IDbConnection并在构造函数中实例化它。
我的问题是,即使IDbCommand没有被包裹在using模式或try-finally中,这是否也确保它被正确地处理了?如果执行命令时发生异常会发生什么?
另外,为了提高性能,在CreateFoo中实例化连接是否比在基类的构造函数中更好?
感谢任何帮助。
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();
}
}
}
继承自该类的类实际上访问数据库:
public class FooDAL : DALBase
{
public int CreateFoo()
{
// Notice that the cmd here is not wrapped in a using or try-finally.
IDbCommand cmd = CreateCommand("create foo with sql", cn);
Open();
int ident = int.Parse(cmd.ExecuteScalar().ToString());
Close();
cmd.Dispose();
return ident;
}
}
使用FooDAL的类使用using模式来确保在像这样的代码上调用Dispose:
using(FooDAL dal = new FooDAL())
{
return dal.CreateFoo();
}
我的问题是,即使IDbCommand没有被包裹在using模式或try-finally中,这是否也确保它被正确地处理了?如果执行命令时发生异常会发生什么?
另外,为了提高性能,在CreateFoo中实例化连接是否比在基类的构造函数中更好?
感谢任何帮助。