How can I implement WCF Transaction support on custom class using CoreService?

荒凉一梦 提交于 2019-12-01 16:23:39

The best resource for this is: WCF Transaction Propagation

You are missing at least one step. You also need to enable transactions in the binding:

<bindings>
   <netTcpBinding>
      <binding name = “TransactionalTCP” transactionFlow = “true” />
   </netTcpBinding>
</bindings>

Is there a way to determine if I am currently in a transaction and somehow "use" that transaction?

Yes. To determine if you are in a transaction you can check Transaction.Current. If you are in a transaction, you will use it unless you explicitly opt out. That's the beautiful/horrible thing about ambient transactions.

Figure 5 in WCF Transaction Propagation:

class MyService : IMyContract 
{
   [OperationBehavior(TransactionScopeRequired = true)]   
   public void MyMethod(...)
   {
      Transaction transaction = Transaction.Current;
      Debug.Assert(transaction.TransactionInformation.
                   DistributedIdentifier != Guid.Empty);
   } 
}

If Transaction.Current.TransactionInformation.DistributedIdentifier is empty, then the transaction is local and didn't "flow". Note that in a TransactionFlowOptions.Allowed configuration if the transaction fails to flow, it fails silently. So this really is the only way to check... and not flowing happens more easily than you would expect.

When I used tranactions for a production service I actually avoided TransactionFlowOptions.Allowed because the caller was never sure if the transaction actually flowed. If there was a binding configuration error in deployment, everything would run fine but rollbacks would fail... a very tendious error to detect. So I switched to required. Then a caller could ensure the transaction they provided was actually passed successfully. (If the transaction doesn't flow in a TransactionFlowOptions.Required configuration you'll get an exception.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!