Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

session-per-request implementation for WCF, NHibernate, and Ninject

I am trying to implement a session-per-request model in my WCF application, and I have read countless documents on this topic, but looks like there is not a complete demonstration of this. I actually came across some very useful articles such as this one:

NHibernate's ISession, scoped for a single WCF-call

but these are all from the old days when NHibernate and Ninject did not have WCF specific implementations, therefore they achieved what I need by implementing their custom service providers, etc. Since both Ninject and NHibernate have WCF support now, I want to keep things consistent by using their modules, but I ended up here...

The basic setup and flow should be something like this:

  1. Set CurrentSessionContext to WcfOperationSessionContext in nhibernate configuration
  2. On service start, begin request, or anywhere around the init time, open session and bind it to the current context
  3. Repositories get the current session instance using SessionFactory.GetCurrentSession() method
  4. Unbind and close session at the end of the lifecycle

My initial problem was that I wasn't able to access to the wcf lifecycle to handle my bindings. After digging into the ninject code a bit, I managed to hook my methods to ServiceHost's Opening / Closing events without changing much, but then I wasn't able to access to the OperationContext since it is thread-static.

Later I tried enabling asp.net compatibility and using Application_BeginRequest and Application_EndRequest, and it looked very promising, but I don't think that's the best solution since I should be binding stuff to the service instance, rather than the http request.

Has anyone ever achieved this using ninject's built-in wcf extension libraries? Or any ideas on what I might be doing wrong?

like image 877
salimaabey Avatar asked Feb 01 '11 20:02

salimaabey


1 Answers

I have implemented per request session lifetime with the help of IDispatchMessageInspector. Probably you could implement custom lifetime manager for Ninject to achieve per web request.

like image 115
Sly Avatar answered Oct 02 '22 20:10

Sly