Advertisement
Guest User

Untitled

a guest
Oct 31st, 2014
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. public interface ICustomSessionLocator : IDependency
  2. {
  3. ISession GetSession();
  4. }
  5.  
  6. public class CustomSessionLocator : ICustomSessionLocator, ICustomTransactionManager, IDisposable
  7. {
  8. private readonly ISessionFactoryBuilder _sessionFactoryBuilder;
  9. private ISession _session;
  10. private ITransaction _transaction;
  11. private bool _cancelled;
  12.  
  13. public CustomSessionLocator(ISessionFactoryBuilder sessionFactoryBuilder)
  14. {
  15. _sessionFactoryBuilder = sessionFactoryBuilder;
  16. Logger = NullLogger.Instance;
  17. IsolationLevel = IsolationLevel.ReadCommitted;
  18. }
  19.  
  20. public ILogger Logger { get; set; }
  21. public IsolationLevel IsolationLevel { get; set; }
  22.  
  23. public ISession GetSession()
  24. {
  25. ((ICustomTransactionManager)this).Demand();
  26. return _session;
  27. }
  28.  
  29. public void Demand()
  30. {
  31. EnsureSession();
  32.  
  33. if (_transaction == null)
  34. {
  35. _transaction = _session.BeginTransaction(IsolationLevel);
  36. }
  37. }
  38.  
  39. public void RequireNew()
  40. {
  41. RequireNew(IsolationLevel);
  42. }
  43.  
  44. public void RequireNew(IsolationLevel level)
  45. {
  46. EnsureSession();
  47.  
  48. if (_cancelled)
  49. {
  50. if (_transaction != null)
  51. {
  52. _transaction.Rollback();
  53. _transaction.Dispose();
  54. _transaction = null;
  55. }
  56.  
  57. _cancelled = false;
  58. }
  59. else
  60. {
  61. if (_transaction != null)
  62. {
  63. _transaction.Commit();
  64. }
  65. }
  66.  
  67. _transaction = _session.BeginTransaction(level);
  68. }
  69.  
  70. public void Cancel()
  71. {
  72. _cancelled = true;
  73. }
  74.  
  75. public void Dispose()
  76. {
  77. if (_transaction != null)
  78. {
  79. try
  80. {
  81. if (!_cancelled)
  82. {
  83. _transaction.Commit();
  84. }
  85. else
  86. {
  87. _transaction.Rollback();
  88. }
  89. }
  90. catch (Exception e)
  91. {
  92. Logger.Error(e, "Error while disposing the transaction.");
  93. }
  94. finally
  95. {
  96. _transaction.Dispose();
  97.  
  98. _transaction = null;
  99. _cancelled = false;
  100. }
  101. }
  102.  
  103. if (_session != null)
  104. {
  105. _session.Dispose();
  106. _session = null;
  107. }
  108.  
  109. }
  110.  
  111. private void EnsureSession()
  112. {
  113. if (_session != null)
  114. {
  115. return;
  116. }
  117.  
  118. _session = _sessionFactoryBuilder.SessionFactory.OpenSession();
  119. }
  120. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement