title: ServiceStack NHibernate and Ninject in Self Hosting App (Request Context)
body: <p>I have a self hosted ServiceStack application, and I try to build ISession per request. I suppose the following will work:</p>
  
  <pre><code>Bind&lt;ISession&gt;()
    .ToMethod(NapraviSesiju)
    .InNamedScope(ControllerScope)
    .InScope(s =&gt; ReuseScope.Request)
    .OnActivation(s =&gt; s.BeginTransaction())
    .OnDeactivation(s =&gt;
  {
    if (!s.Transaction.IsActive) return;
    try
    {
      s.Transaction.Commit();
    }
      catch (Exception e)
    {
      s.Transaction.Rollback();
    }
  });
  
  private ISession NapraviSesiju(IContext kontekst)
  {
    var sesija = kontekst.Kernel.Get&lt;ISessionFactory&gt;().OpenSession();
    return sesija;
  }
  </code></pre>
  
  <p>This works, but request deactivation is not instant (it happens after 30 seconds, or 1 minute, and some requests don't deactivate at all).</p>
  
  <p>Can someone please tell me the correct way to handle NHibernate Sessions this way?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Can I use this then:</p>
  
  <pre><code>public class AppHost : AppHostHttpListenerBase
  {
      private IKernel _jezgro;
  
      public override void Configure(Container container)
      {
          _jezgro = new StandardKernel(new NHibernateModul());
          container.Adapter = new NinjectIocAdapter(_jezgro);
      }
  
      public override void Release(object instance)
      {
          _jezgro.Release(((IHasSession)instance).Sesija);    //Release Sesija from SomeServis object below
      }
  }
  
  public class SomeServis : RestServiceBase&lt;Some&gt;, IHasSession    //implements NHibernate Session
  {
      public ISession Sesija { get; set; }    //IHasSession implementation. Injected by Ninject.
  }
  
  Bind&lt;ISession&gt;()
  .ToMethod(NapraviSesiju)
  .InScope(s =&gt; ReuseScope.Request)   //reuse per request scope. Is this really needed, since release is happening at Release in AppHost?
  .OnActivation(s =&gt; s.BeginTransaction())
  .OnDeactivation(s =&gt;
  {
      if (!s.Transaction.IsActive) return;
      try
      {
          s.Transaction.Commit();
      }
      catch (Exception)
      {
          s.Transaction.Rollback();
      }
  });
  </code></pre>