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,124 | Comments: 45,480

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.


  1. RavenDB 3.5 whirl wind tour: I’ll find who is taking my I/O bandwidth and they SHALL pay - 17 hours from now
  2. The design of RavenDB 4.0: Physically segregating collections - about one day from now
  3. RavenDB 3.5 Whirlwind tour: I need to be free to explore my data - 3 days from now
  4. RavenDB 3.5 whirl wind tour: I'll have the 3+1 goodies to go, please - 6 days from now
  5. The design of RavenDB 4.0: Voron has a one track mind - 7 days from now

And 12 more posts are pending...

There are posts all the way to May 30, 2016


  1. RavenDB 3.5 whirl wind tour (14):
    02 May 2016 - You want all the data, you can’t handle all the data
  2. The design of RavenDB 4.0 (13):
    03 May 2016 - Making Lucene reliable
  3. Tasks for the new comer (2):
    15 Apr 2016 - Quartz.NET with RavenDB
  4. Code through the looking glass (5):
    18 Mar 2016 - And a linear search to rule them
  5. Find the bug (8):
    29 Feb 2016 - When you can't rely on your own identity
View all series


Main feed Feed Stats
Comments feed   Comments Feed Stats