Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public interface ICustomSessionLocator : IDependency
- {
- ISession GetSession();
- }
- public class CustomSessionLocator : ICustomSessionLocator, ICustomTransactionManager, IDisposable
- {
- private readonly ISessionFactoryBuilder _sessionFactoryBuilder;
- private ISession _session;
- private ITransaction _transaction;
- private bool _cancelled;
- public CustomSessionLocator(ISessionFactoryBuilder sessionFactoryBuilder)
- {
- _sessionFactoryBuilder = sessionFactoryBuilder;
- Logger = NullLogger.Instance;
- IsolationLevel = IsolationLevel.ReadCommitted;
- }
- public ILogger Logger { get; set; }
- public IsolationLevel IsolationLevel { get; set; }
- public ISession GetSession()
- {
- ((ICustomTransactionManager)this).Demand();
- return _session;
- }
- public void Demand()
- {
- EnsureSession();
- if (_transaction == null)
- {
- _transaction = _session.BeginTransaction(IsolationLevel);
- }
- }
- public void RequireNew()
- {
- RequireNew(IsolationLevel);
- }
- public void RequireNew(IsolationLevel level)
- {
- EnsureSession();
- if (_cancelled)
- {
- if (_transaction != null)
- {
- _transaction.Rollback();
- _transaction.Dispose();
- _transaction = null;
- }
- _cancelled = false;
- }
- else
- {
- if (_transaction != null)
- {
- _transaction.Commit();
- }
- }
- _transaction = _session.BeginTransaction(level);
- }
- public void Cancel()
- {
- _cancelled = true;
- }
- public void Dispose()
- {
- if (_transaction != null)
- {
- try
- {
- if (!_cancelled)
- {
- _transaction.Commit();
- }
- else
- {
- _transaction.Rollback();
- }
- }
- catch (Exception e)
- {
- Logger.Error(e, "Error while disposing the transaction.");
- }
- finally
- {
- _transaction.Dispose();
- _transaction = null;
- _cancelled = false;
- }
- }
- if (_session != null)
- {
- _session.Dispose();
- _session = null;
- }
- }
- private void EnsureSession()
- {
- if (_session != null)
- {
- return;
- }
- _session = _sessionFactoryBuilder.SessionFactory.OpenSession();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement