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:
[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. 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:
[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: ...