我正在使用事务范围的IEnlistmentNotification接口,我希望在范围完成后访问提交方法中的当前事务ID,如下所示:
public void Commit(Enlistment enlistment)
{
string transactionId = Transaction.Current.TransactionInformation.LocalIdentifier;
enlistment.Done();
}
但是我收到错误,因为现在transaction.current为null。从我检查的登记实例具有transactionId的私有成员,但我无法访问它的保护级别。
在范围完成时是否有另一种获取事务ID的方法?
using (TransactionScope scope = new TransactionScope())
{
using (YourContext context = new YourContext())
{
//DB operations
context.SaveChanges();
}
Transaction.Current.TransactionCompleted += Current_TransactionCompleted;
TransactionInformation info = Transaction.Current.TransactionInformation;
string transactionId = Guid.Empty.Equals(info.DistributedIdentifier) ? info.LocalIdentifier : info.DistributedIdentifier.ToString();
scope.Complete();
}
//For the transaction completed event:
private void Current_TransactionCompleted(object sender, TransactionEventArgs e)
{
//e.Transaction.TransactionInformation contains the Id
}