With NHibernate and Transaction, do I roll back from a commit failure or does it roll back automatically with a single commit?

I built the following Dispose method for my Unit of Work, which essentially wraps the active NH session and transaction (the transaction is set as a variable after opening the session, so as not to be replaced if the NH session receives a new transaction after an error)

public void Dispose() { Func<ITransaction,bool> transactionStateOkayFunc = trans => trans != null && trans.IsActive && !trans.WasRolledBack; try { if(transactionStateOkayFunc(this.transaction)) { if (HasErrored) { transaction.Rollback(); } else { try { transaction.Commit(); } catch (Exception) { if(transactionStateOkayFunc(transaction)) transaction.Rollback(); throw; } } } } finally { if(transaction != null) transaction.Dispose(); if(session.IsOpen) session.Close(); } 

I cannot help but feel that the code is a little bloated, will automatic rollback of a transaction be discrete Commit fails in the case of non-nested transactions?

Automatically or automatically disconnect a transaction? If not Session.Close () will automatically delete the associated transaction?

+4
source share
1 answer

Dispose (), if available, should always be called.

For an NHibernate transaction, Dispose () will cause a rollback if Commit () is already called. You do not need to call rollbacks () if there are no Commit () errors. Although IMHO you should still call Dispose (), if only to follow the pattern.

For the session, asking, "Is Close () Dispose () called?" is a kind of converse. I suspect they might be equivalent, but this is a good form to always call Dispose () on it. You do not need to call Close () separately.

+3
source

All Articles