Click here to Skip to main content
15,893,487 members
Articles / Web Development / ASP.NET

Simple NHibernate Architecture

Rate me:
Please Sign up or sign in to vote.
4.91/5 (38 votes)
11 Sep 2012CPOL3 min read 133.7K   3.2K   145  
An article showing a nice architecture I've come up for using NHibernate
using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using System.Runtime.Remoting.Messaging;

namespace Shared.NHibernateDAL
{
	public class TransactionBlock : IDisposable	
	{
		public TransactionBlock()
		{
			object obj = new object();

			if (ActiveTransactions == 0)
			{
				NHibernateSessionManager.Instance.BeginTransaction();				
			}
			ActiveTransactions++;
		}


		private int ActiveTransactions
		{
			get
			{
				return CallContext.GetData("Active_Transactions") == null ? 0 : Convert.ToInt32(CallContext.GetData("Active_Transactions"));
			}
			set
			{
				CallContext.SetData("Active_Transactions", value);
			}
		}

		private void DisposeActiveTransacions()
		{
			CallContext.SetData("Active_Transactions", null);
		}

		private bool _isValid = false;
		public bool IsValid
		{
			set { _isValid = value; }
		}

		public void Dispose()
		{
			ActiveTransactions--;
			if (_isValid)
			{
				if (_isValid && ActiveTransactions == 0 && NHibernateSessionManager.Instance.GetSession().Transaction.IsActive)
				{
					DisposeActiveTransacions();
					NHibernateSessionManager.Instance.CommitTransaction();
				}
			}
			else if (NHibernateSessionManager.Instance.GetSession().Transaction.IsActive)
			{
				DisposeActiveTransacions();
				NHibernateSessionManager.Instance.RollbackTransaction();
			}
		}

	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Intelligent Coder
Canada Canada
I've been developing .NET enterprise applications since 2000.

I am originally from Rio de Janeiro and I am currently working at http://www.intelligentcoder.com in Ontario.

I also have my own startup where we offer client intake forms.

Comments and Discussions