Click here to Skip to main content
12,998,759 members (67,270 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


15 bookmarked
Posted 17 May 2010

NHibernate sessions in ASP.NET MVC

, 17 May 2010
Rate this:
Please Sign up or sign in to vote.
NHibernate sessions in ASP.NET MVC

If you've used NHibernate in a ASP.NET MVC project, you probably encountered the problem of keeping session open in the view in order to retrieve model data (even though if session is open then the view actually makes calls to the db under the hood, which maybe is not very MVC. But that's another story).

The idea is to pass controllers an instance of a NHibernate session which is unique for the HTTP request.

First off, we need to "hijack" the ASP.NET mechanism that instantiates controllers to pass something in the constructor. In this case, it's a ISession, but it could well be a repository class (which in turn gets a ISession passed in its constructor).

So a controller would look like this:

public class MyController : Controller
    ISession session;

    public MyController(ISession session)
        this.session = session;

I've used Unity dependency container to manage the instantiation of controllers. ASP.NET MVC lets you do that by overriding the DefaultControllerFactory.

This is as simple as writing this class:

public class UnityControllerFactory : DefaultControllerFactory
    UnityContainer container;

    public UnityControllerFactory(UnityContainer container)
        this.container = container;

    protected override IController GetControllerInstance
	(RequestContext requestContext, Type controllerType)
        IController controller = null;
        if (controllerType != null)
            controller = this.container.Resolve(controllerType) as IController;
        return controller;

To make the session instance "singleton" for the HTTP request, all I need to do is write a simple custom lifetime manager for Unity:

public class PerRequestLifetimeManager : LifetimeManager
    public const string Key = "SingletonPerRequest";

    public override object GetValue()
        return HttpContext.Current.Items[Key];

    public override void SetValue(object newValue)
        HttpContext.Current.Items[Key] = newValue;

    public override void RemoveValue() {} // this does not appear to be used ...

Let's get everything together in Global.asax. We need to register ISession in Unity configuration. It should inject it using a factory method (OpenSession method of a ISessionFactory instance).

Then we need to tell MVC to use our Controller factory, passing the Unity container of our ASP.NET MVC application.

To close open sessions, we add some code in the Application_EndRequest.

Here's the code to put in our Global.asax file.

protected void Application_Start()
    this.container = new UnityContainer();
        new PerRequestLifetimeManager(),
        new InjectionFactory(c => {
            ISessionFactory sessionFactory = 
	         NHConfigurator.CreateSessionFactory(); // NHConfigurator is my 
							// helper conf class
            return sessionFactory.OpenSession();

    ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory 



protected void Application_EndRequest(object sender, EventArgs e)
    Object sessionObject = HttpContext.Current.Items[PerRequestLifeTimeManager.Key];
    if (sessionObject != null)
        ISession currentSession = sessionObject as ISession;
        if (currentSession != null)

Hope this helps!


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


About the Author

Software architect. At present working on C# development, with mainly Ajax and MVC user inteface. Particularly interested in OOP, test driven, agile development.

You may also be interested in...

Comments and Discussions

GeneralRe session end Pin
Ajay Kale New9-Sep-10 4:18
memberAjay Kale New9-Sep-10 4:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170622.1 | Last Updated 17 May 2010
Article Copyright 2010 by Giorgio Bozio
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid