9

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

UpTheCreek
  • 31,444
  • 34
  • 152
  • 221
  • Sharp Architecture explains why - it's something with IIS7 as far as I remember. – queen3 Nov 10 '09 at 21:17
  • Well in the code comments it says: "Due to issues on IIS7, the NHibernate initialization must occur in Init().", but I don't know what the issues are. – UpTheCreek Nov 10 '09 at 22:21

2 Answers2

6

Session per Request is probably the most used approach.

sduplooy
  • 14,340
  • 9
  • 41
  • 60
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

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
  • 15,046
  • 12
  • 60
  • 89
  • Hi Sly, but why do you need to use the ASP.NET session state? And why not just put it in Application_Start? – UpTheCreek Nov 11 '09 at 09:48
  • 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 Nov 11 '09 at 10:27
  • Most of the solutions I have been looking at do not use session state, rather HttpContext.Items or a static member. – UpTheCreek Nov 11 '09 at 15:46