【问题标题】:TransactionScope in WCF service or in the client proxy?WCF 服务或客户端代理中的 TransactionScope?
【发布时间】:2012-01-19 11:30:41
【问题描述】:

关于 WCF 服务中的事务,我应该在使用服务的客户端应用程序中还是在服务代码中使用 TransactionScope 对象?请解释原因。

【问题讨论】:

    标签: wcf


    【解决方案1】:

    这取决于您的使用场景。如果你的服务函数执行多个调用,这些调用应该被分组在一个事务中,你应该在你的服务函数中使用Transaction

    当您的客户端调用多个服务功能时,在您的客户端代码中使用 Transaction 非常有用,这些服务功能应该捆绑在一个事务中。

    例如:

    public void MyServiceFunction1()
    {
       using (TransactionScope transaction = new TransactionScope())
       {
          // execute some logic inside this service function that should be in a transaction
       }
    } 
    
    public void MyServiceFunction2()
    {
       using (TransactionScope transaction = new TransactionScope())
       {
          // execute some logic inside this service function that should be in a transaction
       }
    } 
    
    public void MyClientFunction()
    {
       using (TransactionScope transaction = new TransactionScope())
       {
          // Bundle both service calls in one transaction
          MyService service = new MyService();
          service.MyServiceFunction1();
          service.MyServiceFunction2();
       }
    }
    

    但是请注意,您需要正确地configure your WCF bindings 以确保事务从客户端传递到服务器。然后它将在分布式事务中自动提升。

    【讨论】:

      【解决方案2】:

      使服务事务感知意味着如果通过了事务,它将参与其中

      无论谁使用该服务,无论是客户端应用程序还是其他服务,都必须创建一个事务(或已经在流向他们的事务中运行)以供服务登记 - 因此他们必须从 TransactionScope (显式或隐式地让事务流向他们)。

      如果操作被标记为 TransactionFlow(TransactionFlowOption.Allowed) 则消费者不必有事务,但服务不会在流式事务中执行

      如果操作被标记为 TransactionFlow(TransactionFlowOption.Mandatory) 那么客户端必须处理一个事务,并且假设其他位是对齐的(OperationBehavior 创建自动登记等),那么该操作将在同一个分布式事务中运行

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-05
        • 2010-10-31
        • 1970-01-01
        • 1970-01-01
        • 2010-09-22
        相关资源
        最近更新 更多