views:

482

answers:

1

I've built the following Dispose method for my Unit Of Work which essentially wraps the active NH session & transaction (transaction set as variable after opening session as to not be replaced if NH session gets new transaction after 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 can't help feeling that code is a little bloated, will a transaction automatically rollback is a discrete Commit fails in the case of non-nested transactions?

Will Commit or Rollback automatically Dipose the transaction? If not will Session.Close() automatically dispose the associated transaction?

A: 

You should test your specific situation by debugging your code.

You may also like to take a look at UoW.cs as an example of what you probably want to implement.

Martin