I’m setting up my MVC project so that I resolve my ISession‘s on a PerWebRequest basis.
Here’s what I have so far:
In my Castle Windsor Setup I register my ISession using a factory method:
Component.For<ISession>().UsingFactoryMethod(ctx => MsSql2008SessionFactory.OpenSession()).LifestylePerWebRequest()
In my Global.asax Application_Start() I Bind my ISession to NHibernate’s CurrentSessionContext each time a request begins:
BeginRequest += delegate{
CurrentSessionContext.Bind(
MsSql2008SessionFactory.OpenSession());
};
EndRequest += delegate{
var session = MsSql2008SessionFactory
.SessionFactory
.GetCurrentSession();
if (session != null)
{
session.Dispose();
}
CurrentSessionContext
.Unbind(MsSql2008SessionFactory
.SessionFactory);
};
The first time I make a request to a page everything works fine.
The second time I make a request to a page I get an exception stating:
Session is closed! Object name: ‘ISession’.
What am I not doing correctly?
The answer to this turned out to be quite simple.
The repository that I was injecting my
ISessioninto had aSingletonlifestyle.This meant that the
ISessionthat had been injected on the first request was also being used for the subsiquent requests (because my repository class was only being created at the start of the application) and was thus already disposed.