title: session-per-request implementation for WCF, NHibernate, and Ninject
body: <p>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:</p>
  
  <p><a href="http://realfiction.net/go/133" rel="nofollow">NHibernate's ISession, scoped for a single WCF-call</a></p>
  
  <p>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...</p>
  
  <p>The basic setup and flow should be something like this:</p>
  
  <ol>
  <li>Set CurrentSessionContext to WcfOperationSessionContext in nhibernate configuration</li>
  <li>On service start, begin request, or anywhere around the init time, open session and bind it to the current context</li>
  <li>Repositories get the current session instance using SessionFactory.GetCurrentSession() method</li>
  <li>Unbind and close session at the end of the lifecycle</li>
  </ol>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>Has anyone ever achieved this using ninject's built-in wcf extension libraries? Or any ideas on what I might be doing wrong?</p>