title: How do I do nested transactions in NHibernate?
body: <p>Can I do nested transactions in NHibernate, and how do I implement them? I'm using SQL Server 2008, so support is definitely in the DBMS.</p>
  
  <p>I find that if I try something like this:</p>
  
  <pre><code>using (var outerTX = UnitOfWork.Current.BeginTransaction())
  {
      using (var nestedTX = UnitOfWork.Current.BeginTransaction())
      {
          ... do stuff
          nestedTX.Commit();
      }
  
      outerTX.Commit();
  }
  </code></pre>
  
  <p>then by the time it comes to <code>outerTX.Commit()</code> the transaction has become inactive, and results in a ObjectDisposedException on the session AdoTransaction.</p>
  
  <p>Are we therefore supposed to create nested NHibernate sessions instead? Or is there some other class we should use to wrap around the transactions (I've heard of TransactionScope, but I'm not sure what that is)?</p>
  
  <p>I'm now using <a href="https://rhino-tools.svn.sourceforge.net/svnroot/rhino-tools/trunk/commons/Rhino.Commons.NHibernate/UnitOfWork/UnitOfWork.cs" rel="noreferrer">Ayende's UnitOfWork implementation</a> (thanks Sneal).</p>
  
  <p>Forgive any naivety in this question, I'm still new to NHibernate.</p>
  
  <p>Thanks!</p>
  
  <p><strong>EDIT</strong>: I've discovered that you can use TransactionScope, such as:</p>
  
  <pre><code>using (var transactionScope = new TransactionScope())
  {
      using (var tx = UnitOfWork.Current.BeginTransaction())
      {
          ... do stuff
          tx.Commit();
      }
  
      using (var tx = UnitOfWork.Current.BeginTransaction())
      {
          ... do stuff
          tx.Commit();
      }
  
      transactionScope.Commit();
  }
  </code></pre>
  
  <p>However I'm not all that excited about this, as it locks us in to using SQL Server, and also I've found that if the database is remote then you have to worry about having MSDTC enabled... one more component to go wrong. Nested transactions are so useful and easy to do in SQL that I kind of assumed NHibernate would have some way of emulating the same...</p>