title: How to manage a Session as a unit-of-work in NHibernate?
body: <p>After a few years using NHibernate in Winforms and WPF, I still seem to have missed one very important point, which became too obvious when I ran this code snippet:</p>
  
  <pre><code> ISessionFactory sf = Fluently.Configure()
                                .Database(MsSqlConfiguration.MsSql2008
                                  .ConnectionString(c =&gt; c.Is(connectionString)))
                                .Mappings(x =&gt; x.FluentMappings
                                  .AddFromAssemblyOf&lt;MyClass&gt;())
                                .BuildSessionFactory();
  
   for (int i = 0; i &lt; 100; i++)
   {
       new Task(()=&gt;
       {
           Console.WriteLine("{0}, {1}",
             i, 
             sf.OpenSession().QueryOver&lt;MyClass&gt;().List().Count);
       }).Start();
   }
  </code></pre>
  
  <p>This causes a lot of load, I surmise. </p>
  
  <p>Honestly, the only thing I remember having read about Session handling is: Implement Unit Of Work, which proclaims atomar sessions. So, <a href="http://martinfowler.com/eaaCatalog/unitOfWork.html" rel="nofollow">taking a look at the pattern</a>, I have a few concerns/questions.</p>
  
  <ul>
  <li><p>How does lazy loading fit in the picture? If I load my Data using one session, and then close it, lazy loading won't work. So, basically, the unit of work can not close / dispose the Session, meaning it is infinitely large.</p></li>
  <li><p>Sessions have features like <code>IsDirty</code>. If loading and saving objects is done by separate sessions, how can this still be utilized?</p></li>
  </ul>
  
  <p><strong>EDIT:</strong> Oren Eini has stated the very same thing as being a problem in an early <a href="http://msdn.microsoft.com/en-us/magazine/ee819139.aspx" rel="nofollow">article</a> of his. There, he says MicroManaging (=> use and immediate <code>Dispose</code>) cuts off NH functionality like LazyLoading and ChangeTracking. It seems to me though, that UnitOfWork is a Session MicroManagement pattern. So, what's the cleanest solution? Tracking changes myself and using MicroManagement? Monolithic sessions (= Memleak by design)? What if, unlike the example by Oren, you don't have many subdialogs that can restrict session lifetime?</p>