简体   繁体   中英

Which class should be responsible for state and for cleaning up ressources?

I database connection (I guess it could be any statefull ressource) that I create in a parent class and pass to be used in a child class.

Which class should have the responsibility for cleaning up the database connection (making the connection is closed on exception and so on)?

Which class should have the responsibility for the state of the object (open/close connection)?

For instance:

public class Parent
{
    using(var dbConnection = new SqlConnction(connectionString))
    {
        var child = new Child(dbConnection);
        child.MethodUsingTheConnectionPassedInTheConstructor();
    }
}

public class Child
{
    private readonly IDbConnection _dataBaseConnection;

    public Child(IDbConnection dbConnection)
    {
        _dataBaseConnection = dbConnection;
    }

    public MethodUsingTheConnectionPassedInTheConstructor()
    {
        try
        {
            _dataBaseConnection.Open();
            ...
        }
        finally
        {
            _dataBaseConnection.Close();
        }
    }
}

Perhaps it's a good idea to use the provider pattern: Instead of providing the actual connection to the child, you pass in only a description on how to acquire a connection. That way, you can manage resources locally, optimize (shorten) the lifetime of your allocated resources and handle errors locally, too.

If you don't want to use a separate provider class, you could use something like this:

public class Parent
{
    var child = new Child(() => new SqlConnction(connectionString));
    child.MethodUsingTheConnectionPassedInTheConstructor();
}

public class Child
{
    private readonly Func<IDbConnection> _connProvider;

    public Child(Func<IDbConnection> connProvider)
    {
        _connProvider = connProvider;
    }

    public MethodUsingTheConnectionPassedInTheConstructor()
    {
        using(var connection = _connProvider())
        {
        }
    }
}

The class which creates it should be responsible for cleaning it up afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM