3

考虑以下参与分布式事务的 WCF 服务。WCF 的正常行为是在发生任何故障时回滚事务。有没有办法覆盖这种行为?

服务合约:

[ServiceContract]
public interface ITestService {
    [OperationContract]
    [FaultContract(typeof(TestServiceFault))]
    void ThrowError();
    [OperationContract]
    void DoSomething();
    [OperationContract]
    void DoSomethingElse();
}

[DataContract]
public class TestServiceFault{}

服务实现:

class TestService : ITestService {
    [OperationBehavior(TransactionScopeRequired = true)]
    [TransactionFlow(TransactionFlowOption.Mandatory)]
    public void ThrowError() {
        throw new FaultException<TestServiceFault>(new TestServiceFault());
    }
    [OperationBehavior(TransactionScopeRequired = true)]
    [TransactionFlow(TransactionFlowOption.Mandatory)]
    public void DoSomething() {
        //
        // ...
        //
    }
    [OperationBehavior(TransactionScopeRequired = true)]
    [TransactionFlow(TransactionFlowOption.Mandatory)]
    public void DoSomethingElse() {
        //
        // ...
        //
    }
}

客户端实现片段:

using(new TransactionScope()) {
    testServiceClient.DoSomething();

    try {
        testServiceClient.ThrowError();
    } catch(FaultException<TestServiceFault>) {}

    testServiceClient.DoSomethingElse();
}

当从ThrowError()引发 FaultException 时,WCF 回滚分布式事务,其中包括DoSomething()完成的工作。然后,对DoSomethingElse()的客户端调用失败并显示消息The flowed transaction could not be unmarshaled。发生以下异常:事务已被隐式或显式提交或中止。

在我的特定情况下,这种行为是不可取的。我想在客户端捕获异常并继续我的业务。如果发生我没有捕捉到的任何异常,客户端将回滚事务。

注意:这个问题与如何在 WCF 中处理 FaultException 而不中止整个事务?,但接受的答案对我来说并不令人满意 - 所有操作都发生在同一个事务范围内是很重要的。

4

1 回答 1

4

好吧,您可以尝试在服务端设置 TransactionAutoComplete=false,然后使用 SetTransactionComplete() 来防止异常回滚您的工作。

于 2011-02-20T08:19:25.923 回答