Is IDbCommand removed from a class that implements IDisposable?

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()
    {
        // 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 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?

.

+3
2

, , MySqlConnection CreateFOO ( ).

, / .

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());
        }
     }
}
+1

, , , - db DbCommand.

0

Source: https://habr.com/ru/post/1792831/


All Articles