WCF message exchange patterns and implementation of duplex service


What are WCF message exchange patterns?

Message exchange patterns are standard design which tells how the communication between WCF service and client should happen. It decides protocols for communication channels to exchange messages between service and clients and help interoperability.

WCF supports three message exchange patterns which are described below.


  1. One Way

    One Way mep is like short term memory loss, it just fires the execution and forget about the response. It is useful when client do not require the response back like changing status of order, logging some noncritical operations. If you are using MSMQ bindings then One way mep is the best choice for communication as client just needs to call the queue and execution of task is totally depend on queue. For marking the operation as one way use IsOneWay = True.

                    
        [ServiceContract]
        public interface IOrders
        {
            [OperationContract(IsOneWay=true)]
            public void CompleteOrder(int orderID);
        }
                

    Note that using One-way operation contract with fault contract or transaction contexts is not possible.

  2. Request-response

    In Request-response mep client sends message to WCF service and service sends back some response with required processing. This is the most used pattern in SOA as many real time operation requires some status or data back as response. Using this pattern with the void return type operations empty SOAP body will be send to client as response. For marking operation as Request-response you do not have do anything as the default property of IsOneWay is false.

                    
        [ServiceContract]
        public interface IOrders
        {
            [OperationContract]
            public void PlaceOrder(Order order);
        }
                
  3. Duplex

    Duplex pattern is two way message channel where service and client can communicate independently with each other and execute operations. Client should provide the appropriate endpoint using it service should be able to send messages. In real time application Duplex pattern is complicated as it service required active connection and open firewalls of client which is usually avoided because of security. Most of the Duplex contracts requires long running sessions at cost of performance.

                    
        [ServiceContract]
        public interface IOrderDuplexCallback
        {
            [OperationContract(IsOneWay = true)]
            void ShowShipmentDetails(Delivery delivery);    
        }
    
        [ServiceContract(Namespace = "http://NorthwindServices/OrderService", 
            SessionMode=SessionMode.PerSession,
                     CallbackContract=typeof(IOrderDuplexCallback))]
        public interface IOrder
        {
            [OperationContract(IsOneWay = true)]
            void PlaceOrder(Order order);   
        }   
                

The difference between Request-response and Duplex pattern is, Request-response pattern requires the response on same communication channel whereas Duplex will create the separate communication channel to return response to client.


Step by step walkthrough to implement Duplex contract.

This part of article describes step by step defining and creating WCF duplex contracts. Duplex contract enables service and clients communicates each other without depending on each other. Duplex communication requires client to provide channel on which service can trigger operations.

  1. Create WCF Service library

    Create a new WCF Service library as suggested in Create new WCF service library and test using WCFTestClient. This article will give you a basic service implementation.

  2. Add Service Contract

    Duplex contract requires ServiceContracts with One Way and void OperationContract.

    Add new Service Contracts to the project

    Primary contract which will be called by client to service. It uses SessionMode.PerSession to maintain each session data.

                    
        [ServiceContract(Namespace = "http://NorthwindServices/OrderService",
             SessionMode=SessionMode.Allowed,
               CallbackContract=typeof(IOrderDuplexCallback))]
        public interface IOrder
        {
            [OperationContract(IsOneWay = true)]
            void PlaceOrder(Order order);   
        }   
                
    CallbackContract which will be called by service to client. As it is mentioned as callback contract for IOrder WCF will add ServiceContract so no need to mention it explicitly.
        
        public interface IOrderDuplexCallback
        {
            [OperationContract(IsOneWay = true)]
            void ShowShipmentDetails(Delivery delivery);    
        }
                
  3. Duplex Service implementation

    Implement IOrder interface with PlaceOrder operations.

                    
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] 
    public class OrderService : IOrder 
    {       
    public void PlaceOrder(int orderID)
    { 
        //Add code for placing orders 
    
        // In real application you can use it to update clients 
        // as and when the shipping status change. 
    
        // You can call this method from other internal classes 
        // to update shipping like shipped, in  transit, delivered.
        Callback.ShowShipmentDetails(string.Format
        ("Your order has shipped with tracking number {0} ", 22298889844)); 
    }
    
    /// <summar>
    /// Read only public property to give access to callback contract
    /// </summary>
    public IOrderDuplexCallback Callback
    {
        get
        {
            return OperationContext.Current.GetCallbackChannel
                <IOrderDuplexCallback>();
        }
    }
    }
                        
        
  4. Add service endpoint

    Open the app.config file and the endpoint for Order Service. For duplex contract we will use wsDualHttpBinding.

                    
          <services>
          <service name="NorthwindServices.OrderService">
            <host>
              <baseAddresses>
                <add baseAddress = "http://localhost:7741/NorthwindServices
                    /OrderService/" />
              </baseAddresses>
            </host>
            <endpoint address ="" binding="wsDualHttpBinding" 
                contract="NorthwindServices.IOrder">
              <identity>
                <dns value="localhost"/>
              </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" 
                    contract="IMetadataExchange"/>
          </service>
          </services>
                        
                
  5. Host OrderService

    Host this OrderService as suggested in Hosting WCF service in IIS. or hosting in Windows service.

  6. Client Application

    Add the client application as suggested in article for Hosting service in previous step.

  7. Callback client class

    Add a class with name OrderCallback to client application. This class will implement the callback contract interface. Add reference to your service in class by using keyword.

                    
        
        using Northwind.OrderServiceRef;
    
        public class OrderCallback : IOrderCallback  
        {
            public void ShowShipmentDetails(string TrackingID)
            { 
                Console.WriteLine(TrackingID);  
            }
        }
                
  8. Call Service Operation

    Open the program.cs from client console application and add below code. It creates the InstanceContext of callback and hit the service operation.

                    
            static void Main(string[] args)
            {
                OrderCallback callback = new OrderCallback();
                InstanceContext context = new InstanceContext(callback);
                OrderServiceRef.OrderClient client = new OrderClient(context);
                client.PlaceOrder(1234);
                Console.Read(); 
            }
                        
            
  9. Test Service Operation

    Add the break points in OrderCallback.cs and main methods. Run the console application by pressing F5. After calling service operation it calls the ShowShipmentDetails from OrderCallback.cs and print message send by service.

    WCF Service duplex contract output

Speak your mind :
Leave a comment for this article on dotnetbloogers.com
User profile picture on dotnetmentors.com

by siddu at 12/10/2013 6:48:00 PM
Nice article
post comment on dotnetmentors.com