title: Repository pattern with MongoDB - multiple units of work with one transaction
body: <p>I'm implementing a DAL abstraction layer on top of the C# Mongo DB driver using the Repository + Unit of Work pattern.
  My current design is that every unit of work instance opens (and closes) a new Mongo DB session.
  The problem is that Mongo DB only allows a 1:1 ratio between a session and a transaction, so multiple units of work under the same .NET transaction will not be possible.</p>
  
  <p>The current implementation is:</p>
  
  <pre><code>public class MongoUnitOfWork
  {
      private IClientSessionHandle _sessionHandle;
  
      public MongoUnitOfWork(MongoClient mongoClient)
      {
         _sessionHandle = mongoClient.StartSession();
      }
  
      public void Dispose()
      {
         if (_sessionHandle != null)
         {
            // Must commit transaction, since the session is closing
            if (Transaction.Current != null)
              _sessionHandle.CommitTransaction();
            _sessionHandle.Dispose();
         }
      }
  }
  </code></pre>
  
  <p>And because of this, the following code won't work. The first batch of data will be committed ahead of time:</p>
  
  <pre><code>using (var transactionScope = new TransactionScope())
  {
      using (var unitOfWork = CreateUnitOfWork())
      {
         //... insert items
  
         unitOfWork.SaveChanges();
      }  // Mongo DB unit of work implementation will commit the changes when disposed
  
      // Do other things
  
      using (var unitOfWork = CreateUnitOfWork())
      {
         //... insert some more items
         unitOfWork.SaveChanges();
      }
      transactionScope.Complete();
  }
  </code></pre>
  
  <p>Obviously the immediate answer would be to bring all of the changes into one unit of work, but it's not always possible, and also this leaks the Mongo DB limitation.</p>
  
  <p>I thought about session pooling, so that multiple units of work will use the same session, and commit/rollback when the transient transaction completes/aborts.</p>
  
  <p>What other solutions are possible?</p>
  
  <p><strong>Clarification:</strong></p>
  
  <p>The question here is specifically regarding Unit-Of-Work implementation over MongoDB using the MongoDB 4.0 (or later) built-in transaction support.</p>