Transactional Service Programming

For services, WCF offers a simple and elegant declarative programming model. This model is, however, unavailable for non-service code called by services and for non-service WCF clients.

Setting the Ambient Transaction

By default, the service class and all its operations have no ambient transaction. This is the case even when the client’s transaction is propagated to the service. Consider the following service:

interface IMyContract
   void MyMethod();
class MyService : IMyContract
   public void MyMethod()
      Transaction transaction = Transaction.Current;
      Debug.Assert(transaction == null);

The ambient transaction of the service will be null, even though the mandatory transaction flow guarantees the client’s transaction propagation. To have an ambient transaction, for each contract method the service must indicate that it wants WCF to scope the body of the method with a transaction. For that purpose, WCF provides the TransactionScopeRequired property of the OperationBehaviorAttribute:

public sealed class OperationBehaviorAttribute : Attribute,...
   public bool TransactionScopeRequired
   //More members

The default value of TransactionScopeRequired is false, which is why by default the service has no ambient transaction. Setting TransactionScopeRequired to true provides the operation with an ambient transaction: ...

Get Programming WCF Services, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.