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
Create a new ASP.NET web forms or ASP.NET MVC application.
Add a reference to
NHibernate
using NuGet Package Manager Console.If it doesn't exist already, add a new global application class
Global.asax
.In
Global.asax.cs
, add these using statements:using NHibernate; using NHibernate.Cfg; using NHibernate.Context;
Create a static property named
SessionFactory
:public static ISessionFactory SessionFactory { get; private set; }
Now you have two choices. You can either use the companion library, NH4CookbookHelpers
to set up the base configuration or set everything up manually.
Option 1: Using the companion library
Add a reference to
NH4CookbookHelpers
using NuGet Package Manager Console.In the
Application_Start...