sexta-feira, 24 de julho de 2015

NHibernate - TransactionRequired

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;

namespace Lapuinka.Data
{
    public sealed class TransactionRequired : IDisposable
    {
        #region [ Attributes ]
       
        private ITransaction _transaction;
        private readonly bool _shouldCommit;
        private bool _completed;

        #endregion

        #region [ Constructor ]

        public TransactionRequired(ISession session)
        {
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }

            _transaction = session.Transaction;
           
            if (!IsOpenTransaction(_transaction))
            {
                _transaction = session.BeginTransaction();
                _shouldCommit = true;
            }
        }
       
        #endregion

        #region [ Methods ]

        public void Commit()
        {
            if (!_shouldCommit)
            {
                return;
            }

            if (_completed)
            {
                throw new InvalidOperationException("The current transaction is already committed. You should dispose the transaction.");
            }

            _completed = true;

            try
            {
                if (IsOpenTransaction(_transaction))
                {
                    _transaction.Commit();
                    _transaction = null;
                }
            }
            catch (HibernateException)
            {
                RollbackTransaction();
                throw;
            }
        }

        public void RollbackTransaction()
        {
            if (!_shouldCommit)
            {
                return;
            }

            _completed = true;

            if (IsOpenTransaction(_transaction))
            {
                _transaction.Rollback();
            }

            _transaction = null;
        }

        private static bool IsOpenTransaction(ITransaction transaction)
        {
            return transaction != null && transaction.IsActive && !transaction.WasCommitted && !transaction.WasRolledBack;
        }

        #endregion

        #region [ IDisposable Members ]

        public void Dispose()
        {
            if (!_shouldCommit)
            {
                return;
            }

            RollbackTransaction();
        }

        #endregion
    }
}


Postar um comentário