I have a unitofWork class and a repository that uses it something along the lines of this:
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;
}
}
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. 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.
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.