How to dispose NHibernate ISession in an ASP.NET MVC App
Posted
by Joe Young
on Stack Overflow
See other posts from Stack Overflow
or by Joe Young
Published on 2010-01-24T21:08:10Z
Indexed on
2010/04/29
6:07 UTC
Read the original article
Hit count: 535
I have NHibernate hooked up in my asp.net mvc app.
Everything works fine, if I DON'T dispose the ISession. I have read however that you should dispose, but when I do, I get random "Session is closed" exceptions.
I am injecting the ISession into my other objects with Windsor.
Here is my current NHModule:
public class NHibernateHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += context_BeginRequest;
context.EndRequest += context_EndRequest;
}
static void context_EndRequest(object sender, EventArgs e)
{
CurrentSessionContext.Unbind(MvcApplication.SessionFactory);
}
static void context_BeginRequest(object sender, EventArgs e)
{
CurrentSessionContext.Bind(MvcApplication.SessionFactory.OpenSession());
}
public void Dispose()
{
// do nothing
}
}
Registering the ISession:
container
.Register(Component.For<ISession>()
.UsingFactoryMethod(() => MvcApplication.SessionFactory.GetCurrentSession()).LifeStyle.Transient);
The error happens when I tack the Dispose on the unbind in the module. Since I keep getting the session is closed error I assume this is not the correct way to do this, so what is the correct way?
Thanks, Joe
© Stack Overflow or respective owner