交易是建構可靠服務應用程式的關鍵。WCF 提供聲明式交易支援,允許跨服務邊界傳播交易,讓多個服務操作在單一不可分割的交易中完成。本文詳細說明交易流配置、傳播模式與程式設計模型。
僅下列繫結支援交易流:
預設 TransactionFlow = false,需在服務端與客戶端雙方啟用:
<bindings>
<netTcpBinding>
<binding name="TransactionalTCP" transactionFlow="true" />
</netTcpBinding>
</bindings>
注意:TransactionFlow 不會發布至中繼資料,客戶端設定檔需手動啟用。
[ServiceContract]
interface IMyContract
{
[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
void MyMethod(...);
}
public enum TransactionFlowOption
{
NotAllowed, // 預設:禁止傳播
Allowed, // 允許:客戶端有交易則傳播
Mandatory // 強制:必須傳播,且繫結必須啟用交易流
}
| 選項 | 客戶端無交易 | 客戶端有交易 | 繫結需求 |
|---|---|---|---|
| NotAllowed | 服務建立新交易或無交易 | 忽略客戶端交易 | 任意繫結 |
| Allowed | 服務建立新交易或無交易 | 使用客戶端交易 | 客戶端/服務繫結相容即可 |
| Mandatory | 擲回例外 | 使用客戶端交易 | 雙方必須用交易感知繫結並啟用 TransactionFlow |
限制:單向作業 (IsOneWay=true) 不得設為 Allowed/Mandatory,因無回應訊息無法回滾。
System.Transactions.Transaction.Current 取得目前執行緒的環境交易。特性:
LocalIdentifier(永不為 null)、DistributedIdentifier(未提升時為 Guid.Empty)預設服務作業無環境交易。需以 OperationBehaviorAttribute.TransactionScopeRequired 宣告:
class MyService : IMyContract
{
[OperationBehavior(TransactionScopeRequired = true)]
public void MyMethod()
{
Transaction tx = Transaction.Current;
Debug.Assert(tx != null); // 保證有交易
}
}
由三個雙值/三值選項組合:繫結流程、合約流程選項、作業範圍需求。
| 模式 | 繫結流程 | 合約選項 | 範圍需求 | 行為 | 推薦配置 |
|---|---|---|---|---|---|
| Client/Service | True | Allowed | True | 優先用客戶端交易,否則自建 | Allowed + ScopeRequired=true |
| Client | True | Mandatory | True | 必須用客戶端交易 | Mandatory + ScopeRequired=true |
| Service | False/True | NotAllowed | True | 永遠自建新交易 | 無流程屬性 + ScopeRequired=true |
| None | 任意 | 任意 | False | 無環境交易 | ScopeRequired=false (預設) |
Transaction.Current != null(不確定是客戶端還是本地交易)DistributedIdentifier != Guid.Empty(確為分散式交易)DistributedIdentifier == Guid.Empty(本地交易)OperationBehaviorAttribute.TransactionAutoComplete(預設 true)控制自動投票:
TransactionScope 建立根交易:using (var scope = new TransactionScope())
using (var proxy1 = new MyContractClient())
using (var proxy2 = new MyOtherContractClient())
{
proxy1.MyMethod(...);
proxy2.MyOtherMethod(...);
scope.Complete(); // 提交交易
}
WCF 交易支援強大且簡單:透過少量屬性設定選擇邏輯傳播模式。核心決策在於「服務是否應共享客戶端交易」與「服務是否需獨立交易」。理解四種模式權衡,能設計出既可靠又具彈性的分散式系統。