Search content within the blog

Tuesday, August 10, 2010

Implementing transactions in WCF - Part I

Transactional Operations Within a Service
Transactional service operations succeed or fail as a unit. They are initiated
by one party, which assumes that the result will be consistent, whether the
operation succeeds or fails.Figure below depicts pseudo code of this behavior.



The client opens a connection to the service and calls its transfer method. Transfer executes a debit, a credit, and then marks the transaction complete. The client is uninvolved in the transactional semantics.

To implement this behavior in WCF, the service operation must be marked as transactional using the [OperationBehavior(TransactionScoperequired=true)]attribute. This directs WCF to create a new transaction and enlist the execution thread on that transaction before dispatching control to the method. If the operation fails before it is complete, all partial updates to transactional resources within that transaction are rolled back.

if TransactionScoperequired=false is specified, which is the default,the operation executes without a transaction. In that case, the operation will not support ACID properties. If the operation updates one table and then fails updating a second table, updates in the first table will be persisted and the ACID property is violated.

You can indicate that an operation is complete either implicitly or explicitly.
By using the [OperationBehavior(TransactionScoperequired=true)] behavior, the operation is implicitly considered complete if it doesn’t throw an error. If it throws an error, it is considered incomplete and partial updates to transactional resources will be rolled back. Alternatively, you can use the [OperationBehavior(TransactionScoperequired=false)]behavior and then explicitly call
OperationContext.Current.SettransactionComplete() before returning from the method. If you use the explicit method, you also need to use a session-based binding element in the communication channel, and you need to support sessions in the service
contract with [ServiceContract(SessionMode=SessionMode.Allowed)].

Note: The above setting implement Atomic transactions on the calls that are spanning within the same service. If they are calls that span between multiple services within a transaction we need to follow some additional steps. Read "Flowing Transactions Across Operations" to understand it.

No comments:

Post a Comment