Created
September 15, 2011 20:54
-
-
Save johnathan-sewell/1220453 to your computer and use it in GitHub Desktop.
Setting up NHibernate session per web request - Global.asax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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