我正在尝试用C#代码封装事务处理。为此,我创建了一个名为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;
}
}
}
用法:
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();
}
这里的想法是在'using'语句中实例化这个类,并尽快释放与SQL的连接(+完成事务)。经过一番阅读后,我仍然不确定如何在这里处理IDisposable。 TransactionProvider不直接访问任何非托管资源,因此我认为没有理由实现析构函数。我想剩下的唯一事情是确保SQLTransaction和SQLConnection都已完成。以上代码能完成这项工作吗?是否确保在TransactionProvider对象超出范围后立即关闭所有连接?