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: ...
Get Programming WCF Services 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.