title: nHibernate session and multithreading
body: <p>I had a method with a lot of persistence calls that used a nHibernate session, it worked, was alright. But I needed to refactor this method, extracting a method from a content inside a loop, for multithread reasons. Then I created an class with this method. It is like a normal refactoring, but the nHibernate session inside this method call is broken, without context, I didn't finalize it at any moment. <strong>Has nHibernate problems with multithreading?</strong> Even when I have only one more thread executing, I have the same problem.</p>
  
  <p>I use nHibernate Session through a SessionFactory and Façade pattern, it means, the session is not a field of these objects, it is global at SessionFactory.</p>
  
  <hr>
  
  <p>Making it a little bit more clear:</p>
  
  <p><strong>BEFORE:</strong></p>
  
  <pre><code>Method()
  {
  ... persistence calls
  foreach(Thing..)
  {
  ...persistence calls for each thing (1)
  }
  ...
  }
  </code></pre>
  
  <p><strong>AFTER:</strong></p>
  
  <pre><code>Method()
  {
  ... persistence calls
  foreach(Thing..)
  {
  create a thingResolver object with some data
  open a new thread with thingResolver.Method (1)
  starts this thread
  }
  .. waits for finishing threads and continues
  }
  </code></pre>
  
  <hr>
  
  <p>Our nHibernate Session Factory is thread-aware, and stores/retrieves nHibernate session per thread. It is working nicely now ;)</p>