title: How should NHibernate session be handled in Nancy for session-per-request?
body: <p>Really, my my question is in the title... How should NHibernate session be handled in Nancy for session-per-request? If you've got a good answer for that in and of itself, go for it... if you need more background, here it is:</p>
  
  <hr>
  
  <p>I am accustomed to using an actionFilter in ASP.NET MVC to open and close a session in the NHibernate context at the beginning and end of a web request. That way, each database operation within the context of a request uses the same session. </p>
  
  <p>I thought I had the same kind of thing set up in my new project that uses Nancy, but every time a session is needed, a new one is generated. Here's how I'm handling the opening and closing of session in my bootstrapper (inheriting from StructureMapBootstrapper):</p>
  
  <pre><code>protected override void RequestStartup(IContainer container, IPipelines pipelines, NancyContext context)
  {
      var sessionContainer = container.GetInstance&lt;ISessionContainer&gt;();
      pipelines.BeforeRequest.AddItemToStartOfPipeline(x =&gt;
      {
          sessionContainer.OpenSession();
          return x.Response;
      });
      pipelines.AfterRequest.AddItemToEndOfPipeline(x =&gt; sessionContainer.CloseSession());
  }
  </code></pre>
  
  <p>My <code>ISessionContainer</code> is based off of something similar to <a href="http://www.forkcan.com/viewcode/219/UnitOfWork-Action-filter-for-ASPNET-MVC-and-nHibernate" rel="nofollow">this site</a>. My implementation of <code>ISessionContainer</code> uses NHibernate's session context to get the "current session".</p>
  
  <p>Right now, when I try this in my Nancy project, a new session is returned each time the <code>ISessionContainer.Session</code> property is requested. I thought it was because cookie-based sessions are not enabled by default in Nancy, so I added this to my bootstrapper:</p>
  
  <pre><code>protected override void ApplicationStartup(IContainer container, IPipelines pipelines)
  {
      CookieBasedSessions.Enable(pipelines);
  }
  </code></pre>
  
  <p>No dice. I'm still given a new session every time ask for one.</p>
  
  <p>But, really, I don't want to diagnose my problem. I'd rather hear what is the standard way to handle NHibernate session management in Nancy.</p>