views:

306

answers:

2

This is a pretty fundamental question when using NHibernate in a web application, but I don't see any agreed best practice when searching the web. I've seen it done in lots of different places:

Created and disposed in the Repository method - This just seems silly to me, since when you get the object it's already detached.

At the beginning and end of the Controller Action - This seems better, but annoying to have to do it for each action.

At the Application level, in global.asax beginrequest and endrequest - This seems the best idea, but again, I've seen some examples creating in Init instead of beginrequest (sharp architecture for instance) - although I am not sure why.

Maybe there are other approaches?
Can IoC containers help in some way here?
Maybe you know of a good resource on the web regarding this?
And - what method do you use?

Thanks

+3  A: 

Session per Request is probably the most used approach.

Darin Dimitrov
and it works as expected
Jaguar
A: 

I've seen some examples creating in Init instead of beginrequest (sharp architecture for instance) - although I am not sure why.

In IIS 7 You can have access to the Session state in the Init event of Global.asax. That's why sharp arch uses beginrequest.

As for session management I agree with you - Global.asax is the best place for it. Event if you want to have a clean separation between layers and remove DAL settings from UI you can use HttpModule for it.

Also you can have a look at ayende's blog. It explains his way of session management

Sly
Hi Sly, but why do you need to use the ASP.NET session state? And why not just put it in Application_Start?
UpTheCreek
You need session state to store ISession of the NHibernate.You cant do it in Application_Start because you cant have access to the ApplicationState- and you need it to put SessionFactory in it
Sly
Most of the solutions I have been looking at do not use session state, rather HttpContext.Items or a static member.
UpTheCreek