Skip to content

Instantly share code, notes, and snippets.

@johnathan-sewell
Created September 15, 2011 20:54
Show Gist options
  • Save johnathan-sewell/1220453 to your computer and use it in GitHub Desktop.
Save johnathan-sewell/1220453 to your computer and use it in GitHub Desktop.
Setting up NHibernate session per web request - Global.asax
public static ISessionFactory SessionFactory { get; private set; }
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
//Configure NHibernate and create a session factory for the application
var nhibernateConiguration = new NHibernate.Cfg.Configuration();
nhibernateConiguration.Configure();
SessionFactory = nhibernateConiguration.BuildSessionFactory();
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
//Create NHibernate session for this request and bind it to the
//NHibernate session context (configured as web context using HttpContext)
var session = SessionFactory.OpenSession();
NHibernate.Context.CurrentSessionContext.Bind(session);
}
protected void Application_EndRequest(object sender, EventArgs e)
{
//Detach the session from this web request
var session = NHibernate.Context.CurrentSessionContext.Unbind(SessionFactory);
session.Dispose();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment