开发者

Can I prevent WCF from rolling back the transaction when a fault is thrown?

开发者 https://www.devze.com 2023-02-11 06:43 出处:网络
Consider the following WCF service which participates in a distributed transaction.The normal behavior of WCF is to roll back the transaction if any fault occurs.Is there any way to override that beha

Consider the following WCF service which participates in a distributed transaction. The normal behavior of WCF is to roll back the transaction if any fault occurs. Is there any way to override that behavior?

Service contract:

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

[DataContract]
public class TestServiceFault{}

Service implementation:

class TestService : ITestService {
    [OperationBehavior(TransactionScopeRequired = true)]
    [TransactionFlow(TransactionFlowOption.Mandatory)]
    public void ThrowError() {
        throw new FaultExcepti开发者_如何学JAVAon<TestServiceFault>(new TestServiceFault());
    }
    [OperationBehavior(TransactionScopeRequired = true)]
    [TransactionFlow(TransactionFlowOption.Mandatory)]
    public void DoSomething() {
        //
        // ...
        //
    }
    [OperationBehavior(TransactionScopeRequired = true)]
    [TransactionFlow(TransactionFlowOption.Mandatory)]
    public void DoSomethingElse() {
        //
        // ...
        //
    }
}

Client implementation snippet:

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

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

    testServiceClient.DoSomethingElse();
}

When the FaultException is thrown from ThrowError(), WCF rolls back the distributed transaction which includes the work done by DoSomething(). Then, the client call to DoSomethingElse() fails with the message The flowed transaction could not be unmarshaled. The following exception occurred: The transaction has already been implicitly or explicitly committed or aborted.

In my particular scenario this behavior is undesirable. I'd like to catch the exception on the client side and continue about my business. If any exceptions occur that I don't catch, the client will be roll back the transaction.

Note: This question is a duplicate of How to handle a FaultException in WCF without aborting the whole transaction?, but the accepted answer there isn't satisfactory to me - it's important that all of the operations happen within the same transaction scope.


well, you could try setting the TransactionAutoComplete=false on the service side, and then use SetTransactionComplete() to prevent the exception from rolling your work back.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号