我正在尝试将事务处理封装在 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 对象超出范围就会关闭所有连接?