开发者

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

开发者 https://www.devze.com 2023-03-10 10:51 出处:网络
I database connection (I guess it could be any statefull 开发者_如何学Cressource) that I create in a parent class and pass to be used in a child class.

I database connection (I guess it could be any statefull 开发者_如何学Cressource) 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.

0

精彩评论

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

关注公众号