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?