Setting up session-per-web request

Due to its simplicity, the most common pattern used in web applications for managing NHibernate sessions is session-per-request. In this recipe, we'll show you how to set up the session-per-request pattern using NHibernate's contextual sessions feature.

Getting ready

  1. Create a new ASP.NET web forms or ASP.NET MVC application.
  2. Add a reference to NHibernate using NuGet Package Manager Console.
  3. If it doesn't exist already, add a new global application class Global.asax.
  4. In Global.asax.cs, add these using statements:
    using NHibernate;
    using NHibernate.Cfg;
    using NHibernate.Context;
  5. Create a static property named SessionFactory:
    public static ISessionFactory SessionFactory { get; private set; }

Now you have two choices. You ...

Get NHibernate 4.x Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.