Ryan LanciauxNew Media Mercenary

NHibernate Session Per Request

May 11, 2008 by ryan

A little earlier on, I had posted a simple example of NHibernate in an MVC application as well as some initial questions I had about NHibernate Session management. In response to my question, Matt Hinze mentioned that the session should be transparent to the controller and posted some links to various articles explaining how to achieve this. I finally had a chance to play around with this type of session management and spent most of my time looking through Billy McCafferty's NHibernate Best practices on CodeProject. As I've mentioned before, I'm very new to NHibernate so some of the things I'm doing may not be ideal.

HTTP Module

First off, I created an HTTP module; this is where the session will be opened and closed (by accessing the session manager class). You'll notice on the Init that event handlers have been added. I'm using the same session manager class that I was using in my last example, however, now it's being initialized / closed here (rather than in each controller action).

    public class SessionModule : IHttpModule

    {

        private ISession _session;

 

        public void Init(HttpApplication context)

        {

            context.BeginRequest += new EventHandler(OpenSession);

            context.EndRequest += new EventHandler(CloseSession);

        }

 

        private void OpenSession(object sender, EventArgs e)

        {

            _session = SessionManager.GetCurrentSession();

        }

 

        private void CloseSession(object sender, EventArgs e)

        {

            _session.Flush();

            _session.Close();

        }

 

        public void Dispose()

        {

            _session = null;

        }

    }


Next, I added this class to the HttpModules section of the web.config

<add name="SessionModule" type="ProductModel.Session.SessionModule"/>

Controller Code

Finally, since the NHibernate Session is being created / closed in the HTTP Module, I no longer have to use the using statement in every controller. Instead, I'm just setting a ISession = to the SessionManagers Current session.

   public ActionResult AddProduct(string ID)

   {

       ISession session = SessionManager.GetCurrentSession();

       return RenderView("AddProduct",

           new SimpleProductRepository(session).List());

   }

Wrapping Up

There's still a bit more I want to explore with this method of Session Management (maybe transactions). Also I would be interested to test out the threading / performance implications of going this route. I've updated the code on my assembla site. If you're interested, you can check it out here http://svn2.assembla.com/svn/NHibernateTest/ (keep in mind it's demo code -- not anything remotely resembling anything I would use in production). I would really appreciate any suggestions / feedback that you may have!

kick it on DotNetKicks.com  




Related posts

Comments

May 12. 2008 11:44

Joel

Since GetCurrentSession is a static method, do you know how it holds up in threading?

Joel

May 12. 2008 12:53

Pedro Santos

Unfortnatly NHIbernate on ASP.NET isn't that simple. You'll be in troubles if you load some entity and then store it on session/cache/application. The next time you access it, you'll bump into some uninitialized properties and nhibernate will throw a lazy exception:

http://psantos-blog.zi-yu.com/?p=65

Pedro Santos

May 12. 2008 13:03

superjason

Not just that Pedro, but if you try to save it and it has new children, it won't like that.

However, that's a problem regardless of MVC.

(I just looked at your link, and it looks like you talk about that, cool)

superjason

May 12. 2008 13:07

Chad Myers

You might also want to check out Ayende's Rhino Commons since it has a lot of this type of stuff done for you.

He even has functionality built in, when in testing mode, to ensure that a.) One and only one session is opened per request, and that it's closed by the end of the request b.) no query takes over 1 second, etc.

Chad Myers

May 19. 2008 13:29

Billy McCafferty

Hi Ryan,

I've released my next version of my NHibernate best practices code at http://www.codeplex.com/SharpArchitecture ...I'm calling it S#arp Architecture to make it a bit more identifiable. This architecture uses Spring.NET and greatly simplifies the ideas I put forth in my former NHibernate Best Practices article. The orignal announcement is at devlicio.us/.../...-nhibernate-and-spring-net.aspx

Billy McCafferty

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

July 4. 2009 07:17





© 2008 Ryan Lanciaux :: powered by BlogEngine.NET