Transaction and Sessions in Windows Communication Foundation



Introduction:

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

  1. AddOrder method is called and OrderID is returned to client.
  2. OrderID returned by AddOrder method is passed to AddOrderDetails method along with ProductID and Amount.
  3. If no exceptions transaction is complete.

    TWCF1.gif
In this article, we are going to use Sessions so that when Session ends for client proxy and if there is no exception then transaction is completed. Here instead of passing OrderID between client and service, OrderID is maintained in the session itself.

TWCF2.gif

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.

TWCF3.gif

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.

    TWCF4.gif
Step 3: In the OrderService class
  • 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 4: Run the host

TWCF5.gif

Step 5: On client side update service reference.

TWCF6.gif

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

TWCF7.gif

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.
 

Up Next
    Ebook Download
    View all
    Learn
    View all