Search code examples
c#dispose

Where to complete TransactionScope in using statements?


I'm using two SQLConnection in a TransactionScope is this (pseudo)code correct?

using (TransactionScope ts= new TransactionScope(TransactionScopeOption.RequiresNew))
  {
     using (SqlConnection connection1 = new SqlConnection(ConnectionString1))
       {
         (...)
       }

     using (SqlConnection connection2 = new SqlConnection(ConnectionString2))
        {
           (...)
        }

     ts.Complete();
   }

or should I use this one?

using (TransactionScope ts= new TransactionScope(TransactionScopeOption.RequiresNew))
  {
     using (SqlConnection connection1 = new SqlConnection(ConnectionString1))
       {
         (...)
         using (SqlConnection connection2 = new SqlConnection(ConnectionString2))
          {
             (...)
             ts.Complete();
          }
       }
   }

The first code is nicer as it allows me to extract the command in methods. However my fear is that in this case the connections are disposed before the completion of the scope, is the enlistment into the TransactionScope enough to prevent this?


Solution

  • There is no problem at all calling Complete after the nested connections are disposed. The lifetime of the transaction is intentionally larger than that of the SQL connection, and you can continue to interact with it independent of the lifetime of any other connections.

    So yes, in your first example you are calling Complete after the connection is disposed, and that's perfectly fine.

    You can see, based on the examples in the documentation for Transaction Scope as well as this page on how to use transaction scopes that the transaction can be completed after the connection has been disposed.