In this article, I am going to show step by step approach using Transaction and Sessions together in WCF. This article is in continuation with previous article Transaction in WCF(http://www.c-sharpcorner.com/UploadFile/sanks/2083/).
Summary:
In previous article when only Transaction is used within Transaction scope
- AddOrder method is called and OrderID is returned to client.
- OrderID returned by AddOrder method is passed to AddOrderDetails method along with ProductID and Amount.
- If no exceptions transaction is complete.


Let's see now step by step approach in continuation with previous article.
Step 1: In ServiceContract attribute add SessionMode property and set it to Required so that it specifies contract requires binding that supports session.

Step 2: In the Service for ServiceBehavior attribute add:
- InstanceContextMode property and set it to PerSession so that object is created for each session.
- TransactionAutoCompleteOnSessionClose property and set it to true so that pending transaction is complete when session ends without any exception.

- Add private variable OrderID as this OrderID value will be maintained in the session when client calls AddOrder and AddOrderDetails method.
- Make return type of AddOrder to void and in the method implementation set OrderID to value created in the database after insertion into Order table.
- Change AddOrderDetails signature to remove OrderID as input parameter. Here we will get OrderID value that was set when client called AddOrder method.

Step 5: On client side update service reference.

Step 6: On client side, create OrderService client instance within the context of TransactionScope so that when client proxy session ends then session ends.

Conclusion: In this article we have seen that how we can use Transaction with Session so that when session ends without any exception then Transaction also ends.

Ravi SharmaPosted Aug 2, 2010, 8:29 AM
Hi Sanket, This is nice artice I am veryu thankful to youfor this. Regards, Ravi Ranjan Sharma