O'Reilly logo

Programming WCF Services by Juval Lowy

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Transactional Service Programming

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

Ambient Transaction Setting

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

[ServiceContract]
interface IMyContract
{
   [OperationContract]
   [TransactionFlow(TransactionFlowOption.Mandatory)]
   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. In order 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 OperationBehaviorAttribute:

[AttributeUsage(AttributeTargets.Method)]
public sealed class OperationBehaviorAttribute : Attribute,...
{
   public bool TransactionScopeRequired
   {get;set;}
   //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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required