Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL transaction wrapper disposing
    text
    copied!<p>I'm trying to encapsulate transaction handling in C# code. To achieve this I created a class called TransactionProvider. </p> <pre><code>public class TransactionProvider : IDisposable { public SqlTransaction Transaction { get; private set; } private SqlConnection connection; private bool disposed; public TransactionProvider(string connectionString, IsolationLevel isolationLevel, string transactionName) { connection = new SqlConnection(connectionString); connection.Open(); Transaction = connection.BeginTransaction(isolationLevel, transactionName); } public void Dispose() { if (!disposed) { Transaction.Dispose(); connection.Dispose(); disposed = true; } } } </code></pre> <p>Usage:</p> <pre><code>using (TransactionProvider transactionProvider = new TransactionProvider(ProductionRepository.ConnectionString, IsolationLevel.RepeatableRead, "GetPolicyNumbers")) { foreach (Policy policyDetail in policiesDetails) { policyNumbers.Add(GetPolicyNumber(policyDetail.Product, transactionProvider.Transaction)); } transactionProvider.Transaction.Commit(); } </code></pre> <p>The idea here is to instantiate this class in 'using' statement and release connection to SQL (+finish transaction) as soon as possible. After some reading I'm still not sure how to deal with IDisposable here. TransactionProvider does not directly access any unmanaged resources, so I decided that there's no reason to implement a destructor. I guess that the only thing left is to ensure that both SQLTransaction and SQLConnection are getting finalized. Will the above code do the job? Does it ensure that all connections will be closed as soon as TransactionProvider objects go out of scope?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload