Windows Communication Foundation (WCF) 应用程序可以从客户端内启动事务,并在服务作中协调事务。 客户端可以启动事务和调用多个服务操作,并可确保服务操作作为一个单元提交或回滚。
通过指定ServiceBehaviorAttribute 并设置其 TransactionIsolationLevel 和 TransactionScopeRequired 属性,可以为需要客户端事务的服务操作启用服务协定中的事务行为。 TransactionAutoComplete 参数指定如果没有引发未处理的异常,方法执行的事务是否自动完成。 有关这些属性的详细信息,请参阅 ServiceModel 事务属性。
在服务操作中执行并由资源管理器管理的工作(例如记录数据库更新)是客户端事务的一部分。
下面的示例演示了如何使用 ServiceBehaviorAttribute 和 OperationBehaviorAttribute 属性来控制服务端事务行为。
[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();
}