服务和事务

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();  
}  

另请参阅