Sunday, July 14, 2013

Transactions in WCF Service

A. Changes in WCF service to support Transactions

Step 1:
Create a method in Interface and add transaction attribute “[TransactionFlow(TransactionFlowOption.Allowed)]” on it.

[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
void InsertEmployee(employee emp);

Step 2:
In service class add operation behaviour on method to enable transaction

[OperationBehavior(TransactionScopeRequired=true)]
public void InsertEmployee(employee emp)
{
}

Step 3:
In Service app config, add wsHHTPBinding end point
<endpoint address ="http://localhost:8731/Design_Time_Addresses/WcfServiceLibrary1/Service1/" binding="wsHttpBinding" bindingConfiguration="TransactionalBind" contract="WcfServiceLibrary1.IService1">

Step 4:
Create binding configuration and add its name in endpoints under “binding configuration” property
<bindings>
      <wsHttpBinding>
        <binding name="TransactionalBind" transactionFlow="true"></binding>
      </wsHttpBinding>
</bindings>


B. Changes while consuming WCF service in Web Application:

Step 1:
Consume the WCF service by adding reference

Step 2:
Add transaction scope in method

        using (TransactionScope a = new TransactionScope(TransactionScopeOption.RequiresNew))
        {
            try
            {
                obj.InsertEmployee(new ServiceReference1.employee());
                //throw new Exception();
                a.Complete();
            }
            catch
            {
                a.Dispose();
            }
        }
       Transaction will complete when complete method will call in transaction scope.In case of any exception it’ll rollback the transaction done.






No comments:

Post a Comment