Ayende @ Rahien

My name is Oren Eini
Founder of Hibernating Rhinos LTD and RavenDB.
You can reach me by phone or email:


+972 52-548-6969

, @ Q c

Posts: 6,007 | Comments: 44,760

filter by tags archive

Refactoring toward frictionless & odorless codeLimiting session scope

time to read 4 min | 795 words

Originally posted at 3/30/2011

In the previous posts, we have looked at how we are going to setup an application using NHibernate. We set it up using:

    public MvcApplication()
        BeginRequest += (sender, args) =>
            CurrentSession = sessionFactory.OpenSession();
        EndRequest += (o, eventArgs) =>
            var session = CurrentSession;
            if (session != null)

But this code is problematic. It is problematic because the session is open for the lifetime of the request. That is a problem, but probably not because of what you think. The #1 reason for issues like Select N+1 is people accessing lazy loaded properties in the views.

One good way of avoiding that is limiting the session scope only to the action, so when rendering the view, the session is not available. Therefor, every attempt to lazy load, will immediately throw. With ASP.Net MVC, this is very easy:

public class NHibernateActionFilter : ActionFilterAttribute
    private static readonly ISessionFactory sessionFactory = BuildSessionFactory();

    public static ISession CurrentSession
        get { return HttpContext.Current.Items["NHibernateSession"] as ISession; }
        set { HttpContext.Current.Items["NHibernateSession"] = value; }

    private static ISessionFactory BuildSessionFactory()
        return new Configuration()

    public override void OnActionExecuting(ActionExecutingContext filterContext)
        CurrentSession = sessionFactory.OpenSession();

    public override void OnActionExecuted(ActionExecutedContext filterContext)

        var session = CurrentSession;
        if (session != null)

We need to modify the SessionController as well, so it would now be:

public class SessionController : Controller
     public HttpSessionStateBase HttpSession
          get { return base.Session; }

     public new ISession Session { get { return NHibernateActionFilter.CurrentSession; } }

Of course, we have broken the HomeController now, but we will discuss how in the next post.

More posts in "Refactoring toward frictionless & odorless code" series:

  1. (12 Apr 2011) What about transactions?
  2. (11 Apr 2011) Getting rid of globals
  3. (10 Apr 2011) The case for the view model
  4. (09 Apr 2011) A broken home (controller)
  5. (08 Apr 2011) Limiting session scope
  6. (07 Apr 2011) Hiding global state
  7. (06 Apr 2011) The baseline



This implies we'll have different sessions for child actions. Is this benign?

The good point is thanks to the new ASP.Net MVC 3 Global Filters, we won't have to decorate every controller with the NHibernateActionFilterAttribute.



Of course it is not. The scenario goes like:

  • parent action creates and stores a session in a context

  • child action creates and overrides parent's session in a context

  • child action disposes the session

  • the parent action is left with a handful of nothing, a disposed session.

The better solution is to use http modules with Castle disposing module (at the end of a request). It is fired once, at the end of parent request and allows you to use the same session (first level cache).

Ryan Heath


I think each child action creates its own session and disposes it. Also the parent action disposes its own session.

Because when child actions are invoked from the view the parent action has already disposed its session.

The sequence is like:

  • parent OnActionExecuting

  • parent Action

  • parent OnActionExecuted

  • viewResult is executed: any child action in the view goes through the same sequence.

// Ryan



yes, you're right! The child actions are executed when a parent's action result is executed. Your ordering is right. It does not change the fact, that first level cache optimization is lost, and that was the point behind my comment :)


Sorry if this sounds thick, but is there a danger of overlapping requests sharing the same session and one disposing a session that is still being used? If that makes sense?



Items are held by current request, so as far as I see your point: not, there can be no cross-request problem.

Dominic Pettifer

Not sure I agree with the approach (in fact I don't), there are better ways to solve the Select N + 1 problem, such as strongly typed ViewModels. Plus in real world apps I build, I'm rarely sending just a collection domain models/entities to the View, it usually includes a bunch of other things, hence the argument for ViewModels.


@Scooletz Thanks, that makes sense


Look at the right, Future Post number 2 :)


I'm still up in the air on how I'm going to handle session scope in my next project. It's nice to have it open in view for child actions, but this can lead to many select N+1 in view code if you're too lazy to map a domain object to viewmodel. Child actions are just sooo convenient for a complex site.master menu...so, it really comes down to not being lazy with your view models.

Dominic Pettifer


Well spotted, I didn't see that :-)


+1 for a view model. unless you're app is intended to be a super simple layer over db crud off course.

Arnis Lapsa

Now that's a really good tip!

Comment preview

Comments have been closed on this topic.


No future posts left, oh my!


  1. Speaking (3):
    23 Sep 2015 - Build Stuff 2015 (Lithuania & Ukraine), Nov 18 - 24
  2. Production postmortem (11):
    22 Sep 2015 - The case of the Unicode Poo
  3. Technical observations from my wife (2):
    15 Sep 2015 - Disk speeds
  4. Find the bug (5):
    11 Sep 2015 - The concurrent memory buster
  5. Buffer allocation strategies (3):
    09 Sep 2015 - Bad usage patterns
View all series



Main feed Feed Stats
Comments feed   Comments Feed Stats