Nhibernate with ASP.Net

So here I am continuing to express my love for NHibernate after my first post Falling in Love with nhibernate . If you are new to this wonderful concept , I would recommend to read my first post to get and idea  and then you can have a look at the documentation available on Nhibernate Home page .

you can download Nhibernate 3.0 form here

This is needless to explain , a web request have its own http session and everything works more or less on this session. Another things to be noted is that we NHibernate also has its own session. Now whenever we need to access nhibernate session from our web application (i.e. Asp.net web app ) we need to bind nhibernet session with the web request session so that we can ask from NHibernate session , what we have asked in a specific web request .

This is little bit tricky but not so difficult . To achieve the above scenario we need to write few lines of code in our Global.asax file and implement IHttpModule interface .

public class Global : System.Web.HttpApplication
public static ISessionFactory SessionFactory { get; private set; }
void Application_Start(object sender, EventArgs e)

var config = new Configuration();
// new SchemaExport(config).Execute(false, true, false);
SessionFactory = config.BuildSessionFactory();


public class NHibernateSessionModule : IHttpModule
public void Dispose()
public void Init(HttpApplication context)
context.BeginRequest +=
var session = Global.SessionFactory.OpenSession();
context.EndRequest +=

Now after implementing IHttpModule  we are almost done. Note that we bind the nhibernate session with the HttpApplicationContext and unbind it when the  request is completed. Binding session with HttpApplicationContext is not a costly operation.

Now when i need nhibernate session for some operation , i need to get it from the Global.asax like : Global.SessionFactory.GetCurrentSession()

I have created a small sample application to make it easy to understand the above techie story . Your can down load the same NhibernateWithAspNet form here

You can also download the Nhibernet with N Unit test application form here

I agree that many of you will not like this approach of using NHibernate directly in the web application. But this post is just to give an idea ands small learning of the behavior of nhibernet session and web request session. I will post “NHibernate with Repository patterns” soon..


Note : please change the database connection settings in web.config file to run the application

2 thoughts on “Nhibernate with ASP.Net

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s