开发者

Does IDbCommand get disposed from within a class that implements IDisposable?

开发者 https://www.devze.com 2023-02-10 21:55 出处:网络
I have a base class for data access classes.This class implements IDisposable. This base class contains the IDbConnection and instantiates it in the constructor.

I have a base class for data access classes. This class implements IDisposable. This base class contains the IDbConnection and instantiates 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();
        }
    }
}

Classes that inherit from this class actually access the database:

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;
    }
}

Classes that use FooDAL use the using pattern to ensure that Dispose gets called on the FooDAL with code like this:

using(FooDAL dal = new FooDAL())
{
    return dal.CreateFoo();
}

My question is, does this also ensure that th开发者_开发问答e IDbCommand is disposed of properly even though it's not wrapped in a using pattern or try-finally? What happens if an exception occurs during the execution of the command?

Also, would it be better to instantiate the connection in CreateFoo instead of in the constructor of the base class for performance reasons?

Any help is appreciated.


Given that the connections are pooled, just create the MySqlConnection in the CreateFOO method (with a using block).

Don't bother about closing it, as it will be disposed/closed automatically at the end of the using block.

public int CreateFoo()
{
    using (var cn = new MySqlConnection(connString))
    {
        // Notice that the cmd here is not wrapped in a using or try-finally.
        using (IDbCommand cmd = CreateCommand("create foo with sql", cn))
        {
            cn.Open();
            return int.Parse(cmd.ExecuteScalar().ToString());
        }
     }
}


If this is all in the interest of efficiency, the biggest change you can make to speed up your code is to avoid opening and closing the db connection object on each DbCommand.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号