共用方式為


服務和交易

Windows Communication Foundation (WCF) 應用程式可以從用戶端內起始交易,並協調服務作業內的交易。 用戶端可以起始交易並叫用數個服務作業,並確保服務作業已認可或回復為單一單位。

您可以透過指定ServiceBehaviorAttribute,並為需要用戶端交易的服務作業設定其TransactionIsolationLevelTransactionScopeRequired屬性,以在服務合約中啟用交易行為。 參數 TransactionAutoComplete 指定該方法執行的交易,如果沒有擲回未處理的例外狀況,是否會自動完成。 如需這些屬性的詳細資訊,請參閱 ServiceModel 交易屬性

在服務作業中執行的工作,並由資源管理員管理,例如記錄資料庫更新,是用戶端交易的一部分。

下列範例展示了如何使用 ServiceBehaviorAttributeOperationBehaviorAttribute 屬性來控制伺服器端的交易行為。

[ServiceBehavior(TransactionIsolationLevel = System.Transactions.IsolationLevel.Serializable)]  
public class CalculatorService: ICalculatorLog  
{  
    [OperationBehavior(TransactionScopeRequired = true,  
                           TransactionAutoComplete = true)]  
    public double Add(double n1, double n2)  
    {  
        recordToLog($"Added {n1} to {n2}");
        return n1 + n2;  
    }  
  
    [OperationBehavior(TransactionScopeRequired = true,
                               TransactionAutoComplete = true)]  
    public double Subtract(double n1, double n2)  
    {  
        recordToLog($"Subtracted {n1} from {n2}");
        return n1 - n2;  
    }  
  
    [OperationBehavior(TransactionScopeRequired = true,
                                       TransactionAutoComplete = true)]  
    public double Multiply(double n1, double n2)  
    {  
        recordToLog($"Multiplied {n1} by {n2}");
        return n1 * n2;  
    }  
  
    [OperationBehavior(TransactionScopeRequired = true,
                                       TransactionAutoComplete = true)]  
    public double Divide(double n1, double n2)  
    {  
        recordToLog($"Divided {n1} by {n2}", n1, n2);
        return n1 / n2;  
    }  
  
}  

您可以將用戶端和服務綁定設定為使用 WS-AtomicTransaction 協議,並將<transactionFlow>元素設true為啟用交易和交易流程,如下列範例設定所示。

<client>  
    <endpoint address="net.tcp://localhost/ServiceModelSamples/service"
          binding="netTcpBinding"
          bindingConfiguration="netTcpBindingWSAT"
          contract="Microsoft.ServiceModel.Samples.ICalculatorLog" />  
</client>  
  
<bindings>  
    <netTcpBinding>  
        <binding name="netTcpBindingWSAT"  
                transactionFlow="true"  
                transactionProtocol="WSAtomicTransactionOctober2004" />  
     </netTcpBinding>  
</bindings>  

客戶可以在交易範圍內建立 TransactionScope 並叫用服務作業,以開始交易。

using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew))  
{  
    //Do work here  
    ts.Complete();  
}  

另請參閱