简体   繁体   English

工作单元,存储库和连接的处置

[英]unitofwork, repositories and disposing of connections

I have a unitofWork class and a repository that uses it something along the lines of this: 我有一个unitofWork类和一个使用该类的存储库:

unit of work 工作单位

private SqlConnection _conn;
private TransactionScope _ts;

public UnitOfWork(SqlConnection conn, TransactionScope ts)
{
    _ts = ts;
    _conn = conn;
    _conn.EnlistTransaction(Transaction.Current);
}

public SqlConnection Connection
{
    get { return _conn; }
}

public void Save()
{
    _ts.Complete();
}

#region IDisposable

public void Dispose()
{
    if (_conn != null)
    {
        _conn.Dispose();
        _conn = null;
    }

    if (_ts != null)
    {
        _ts.Dispose();
        _conn = null;
    }
}

repository 资料库

SqlConnection _conn;

public Repository(IUnitOfWork uow)
{
    _conn = uow.Connection;
}
// some methods
public void Dispose()
{
    if (_conn != null)
    {
        _conn.Dispose();
        _conn = null;
    }
}

I am using it like this 我正在这样使用

using (var uow = new UnitOfWork())
{
    using (var repo = new Repository(uow))
    {
        if (repo.UpdateStuff())
        {
            uow.Save();
        }
    }
}

the dispose method is first called in the repo, which disposes and nulls the connection. 首先在存储库中调用dispose方法,该方法处理并清空连接。 but then when it we get to the uow dispose, the connection is no longer null and is disposed 'again' I am sure I am being dull, but can anyone explain please 但是,当我们开始处置时,连接不再为空,并且再次“处置”,我确定我很呆板,但是任何人都可以解释一下

thanks 谢谢

The right part of the statement 声明的正确部分

_conn = uow.Connection;

actually returns a copy of the object reference, not the reference itself. 实际上返回对象引用的副本,而不是引用本身。

So what you're setting to null in the Repository Dispose method is the local reference to the connection, which is different from the connection reference in the UnitOfWork instance. 因此,在Repository Dispose方法中设置为null的是对连接的本地引用,这与UnitOfWork实例中的连接引用不同。

If you really want to keep this behavior ( having the UnitOfWork Connection property set to null by the Repository Code), you must set the uow.Connection to null, not the local reference _conn. 如果您确实想保留此行为(存储库代码将UnitOfWork Connection属性设置为null),则必须将uow.Connection设置为null,而不是本地引用_conn。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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