0

I'm trying to encapsulate transaction handling in C# code. To achieve this I created a class called TransactionProvider.

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;
        }
    }
}

Usage:

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();
}

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?

borkovski
  • 938
  • 8
  • 12
  • But Why are you using disposed flag?? – vendettamit Oct 02 '13 at 08:24
  • I guess I left the flag after trying multiple implementations of IDisposable as an attempt to prevent multiple Dispose() calls to SQLConnection and SQLTransaction. Now that you mentioned it, there's probably no need for it in current form. Thanks for feedback! – borkovski Oct 02 '13 at 08:33

0 Answers0