How to Initiate a WCF Transaction on the Client Application

Sometimes it is sufficient to start transactions at service boundaries. At other times, you must create client applications (Windows-based applications or other services) that take control of their own transactions.

Client
Client applications that use your WCF service will often implement business logic. The business logic will often include functionality that should only succeed as a complete logical unit. If your client application contains functionality that should only complete as a logical unit, your client application can initiate a transaction. For example, if your client application includes business logic that includes calling three operations on your WCF service, you can use a transaction to group the calls. Different client applications in your organization will expose different business logic, so you can create different transactions in each application to satisfy your business needs

Service
It is usually better to keep transactional interaction on the server side because the client computer may be widely distributed or may not be able to run the DTC or equivalent transaction controller. In this case, the service methods that constitute the transaction are batched together as part of an operation on another service that is specifically designed to manage such groups of operations. Such a service operation is usually referred to as a façade after the Façade design pattern.

To start a transaction on the client application, use System.Transactions.TransactionScope. You create the TransactionScope class to execute the commands. This guarantees that multiple commands can commit or roll back as a single unit of work. If the command succeeds, the Complete method commits the transaction; otherwise, the transaction is rolled back.

The following code example shows how to initiate a transaction from a client application by using the TransactionScope class and the TransactionScopeOption enumeration.

[Visual Basic]

...

 

Using tx As _

    New TransactionScope(TransactionScopeOption.RequiresNew)

    ...

End Using

 

...

 

[Visual C#]

...

 

using (TransactionScope tx =

    new TransactionScope(TransactionScopeOption.RequiresNew))

{

    ...

}

 

...

 

For more information, see Features Provided by System.Transactions and TransactionScope Class