I have code analysis turned on and telling me to implement Dispose()
correctly:
Modify 'UnitOfWork.Dispose' so that it calls Dispose(true), then calls GC.SuppressFinalize on the current object instance
It's actually implemented correctly, except for an additional line of code. See the first line (rolling back the transaction) in Dispose()
. If I comment that line, the CA error goes away. If the line is uncommented, I get the error. Am I not allowed to have that line in Dispose()
?
public void Dispose()
{
// If the user never called commit, but we are using a transaction, then roll back.
// If I comment this line, then the CA error about implementing `Dispose()` correctly goes away.
if (!_commitOccurred && _useTransaction) { _transaction.Rollback(); }
Dispose(true);
GC.SuppressFinalize(this); // Already disposed; no need for the GC to finalize.
}
protected virtual void Dispose(bool calledFromDisposeAndNotFromFinalizer)
{
if (_disposed) { return; }
if (calledFromDisposeAndNotFromFinalizer)
{
if (_transaction != null) { _transaction.Dispose(); _transaction = null; }
if (_connection != null) { _connection.Dispose(); _connection = null; }
}
_disposed = true;
}
Cleanup code goes in the overloaded Dispose
:
protected virtual void Dispose(bool calledFromDisposeAndNotFromFinalizer)
{
if (_disposed) { return; }
if (calledFromDisposeAndNotFromFinalizer)
{
if (!_commitOccurred && _useTransaction) { _transaction.Rollback(); }
if (_transaction != null) { _transaction.Dispose(); _transaction = null; }
if (_connection != null) { _connection.Dispose(); _connection = null; }
}
_disposed = true;
}
At very least this guarantees that redundant calls don't re-enter.