服务和事务

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(String.Format("Added {0} to {1}", n1, n2));
        return n1 + n2;
    }

    [OperationBehavior(TransactionScopeRequired = true, 
                               TransactionAutoComplete = true)]
    public double Subtract(double n1, double n2)
    {
        recordToLog(String.Format("Subtracted {0} from {1}", n1, n2));
        return n1 - n2;
    }

    [OperationBehavior(TransactionScopeRequired = true, 
                                       TransactionAutoComplete = true)]
    public double Multiply(double n1, double n2)
    {
        recordToLog(String.Format("Multiplied {0} by {1}", n1, n2));
        return n1 * n2;
    }

    [OperationBehavior(TransactionScopeRequired = true, 
                                       TransactionAutoComplete = true)]
    public double Divide(double n1, double n2)
    {
        recordToLog(String.Format("Divided {0} by {1}", 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();
}

另请参见

任务

WS 事务流

概念

事务模型

其他资源

System.ServiceModel 中的事务性支持