Message Exchange Patterns In WCF Service

In this article, we will see what message exchange in WCF is and what are the patterns available to exchange the message. We will also see how to do it.

What is Message Exchange Pattern?

It is nothing but something that describes how the client and service will exchange the messages between them. In WCF, there are three types of patterns available to exchange the message:

  1. Request and response
  2. One-way communication
  3. Duplex communication

Request and Response Pattern

The client will send the request to the WCF service and the service will return the response back to the client after completing the operation in service. The client will wait for the service response during this time. It will happen even if the method is void in the operation contract.

All WCF bindings will support the request –response pattern except MSMQ. During this communication the client will get an exception if it occurs in service.

This is the default message exchange pattern in WCF, if we do not specify anything in the WCF service.

Sample

  1. [ServiceContract]  
  2. public interface IHelloService  
  3. {  
  4.     [OperationContract]  
  5.     string SayHello(string name);  
  6. }  
OR
  1. [ServiceContract]  
  2. public interface IHelloService  
  3. {  
  4.    [OperationContract(IsOneWay=false)]  
  5.    string SayHello(string name);  
  6. }  
Note the above two codes. In one operation contract I mentioned the IsOneWay property as false and I did not mention it in another one. Both are equal in WCF. The default message exchange pattern is request-reply in WCF.

One-way communication

The client only sends the request to the service and it will not wait for the response back from the service. The client will not get any exceptions if it is occurring during the service processing it, because the client is not waiting for the result here.

Here, the client will not wait for the response from the service. The service operation’s return type may be anything. But we can’t get the result in the client.

Sample Code

  1. [ServiceContract]  
  2. public interface IUser  
  3. {  
  4.     [OperationContract(IsOneWay = true)]  
  5.     void ChangeLoginState(bool state);  
  6. }  
  7. public class User: IUser  
  8. {  
  9.     void IUser.ChangeLoginState(bool state)  
  10.     {  
  11.         Thread.Sleep(7000);  
  12.     }  
  13. }  
Client application code
  1. ServiceRef.UserClient client = new ServiceRef.UserClient();  
  2. client.ChangeLoginState(true);  
  3. Console.ReadKey();  
Here we will find the difference between request-reply and one way communication by setting the IsOneWay property as false in the operation contract.

Duplex Communication

The client sends a request in one channel and the server will send a response in another channel. The service exception may or may not be thrown to the client depending on the implementation.

We will implement the duplex communication in two ways.

First Way

Step 1: Create service library and add the service and callback interface as below.
  1. [ServiceContract(CallbackContract = typeof (IStatusCallBack))]  
  2. public interface IStatusServie  
  3. {  
  4.     [OperationContract(IsOneWay = true)]  
  5.     void NotifyStatus();  
  6. }  
  7. public interface IStatusCallBack  
  8. {  
  9.     [OperationContract(IsOneWay = true)]  
  10.     void Progress(int percent);  
  11. }  
The callback interface only has the operation contract without service contract attributes and both the operation contract marked with IsOneWay property. Here they are going to communicate independently.

Step 2:
Add the one console project to host the service in self host and implement the following code in the class.
  1. Console.WriteLine("Try to start service.");  
  2. ServiceHost host = new ServiceHost(typeof (DuplexService.StatusServie));  
  3. host.Open();  
  4. Console.WriteLine("The service started successfully.");  
  5. Console.ReadKey();  
Step 3: Add the following configuration in service host project.
  1. <system.serviceModel>  
  2.     <services>  
  3.         <service name="DuplexService.StatusServie" behaviorConfiguration="mexBehaviour">  
  4.             <endpoint address="StatusServie" binding="netTcpBinding" contract="DuplexService.IStatusServie"></endpoint>  
  5.             <host>  
  6.                 <baseAddresses>  
  7.                     <add baseAddress="http://localhost:8085" />  
  8.                     <add baseAddress="net.tcp://localhost:8086" /> </baseAddresses>  
  9.             </host>  
  10.         </service>  
  11.     </services>  
  12.     <behaviors>  
  13.         <serviceBehaviors>  
  14.             <behavior name="mexBehaviour">  
  15.                 <serviceMetadata httpGetEnabled="true" /> </behavior>  
  16.         </serviceBehaviors>  
  17.     </behaviors>  
  18. </system.serviceModel>  
Step 4: Build the application and run the server project in the administrator mode.

Step 5: Now the service will be running. Create one client project and capture the service using the URL http://localhost:8085.

Step 6: Implement the following code in the client application and run it.
  1. class Program: ServiceRef.IStatusServieCallback  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         Program p = new Program();  
  6.         p.CallCallBackService();  
  7.         Console.ReadKey();  
  8.     }  
  9.     public void CallCallBackService()  
  10.     {  
  11.         InstanceContext callBack = new InstanceContext(this);  
  12.         ServiceRef.StatusServieClient client = new ServiceRef.StatusServieClient(callBack);  
  13.         client.NotifyStatus();  
  14.     }  
  15.     public void Progress(int percent)  
  16.     {  
  17.         Console.WriteLine(percent + "% Comppleted.");  
  18.     }  
  19. }  
Note here. We implement the callback contract in the client and mentioned in the service instance.

Now you will see the output to the application like this.

cmd

It will print from 1 to 100. The same duplex code we will implement in another way without mentioning the IsOneWay Property. Let us see it.

Second Way

Step 1:
Implement the same service code without mentioning the IsOneWay property;
  1. [ServiceContract(CallbackContract = typeof (IStatusCallBack))]  
  2. public interface IStatusServie  
  3. {  
  4.     [OperationContract]  
  5.     void NotifyStatus();  
  6. }  
  7. public interface IStatusCallBack  
  8. {  
  9.     [OperationContract]  
  10.     void Progress(int percent);  
  11. }  
Step 2: In the service implementation class mention the attribute ServiceBehavior as mentioned below,
  1. [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]  
  2. public class StatusServie: IStatusServie  
  3. {  
  4.     public void NotifyStatus()  
  5.     {  
  6.         for (int i = 1; i <= 100; i++)  
  7.         {  
  8.             Thread.Sleep(50);  
  9.             OperationContext.Current.GetCallbackChannel < IStatusCallBack > ().Progress(i);  
  10.         }  
  11.     }  
  12. }  
Step 3: There is no difference in the server host code. Just run it and capture in the client application and implement the client code with the attribute CallbackBehavior.
  1. [CallbackBehavior(UseSynchronizationContext = false)]  
  2. class Program: ServiceRef.IStatusServieCallback  
  3. {  
  4.     static void Main(string[] args)  
  5.     {  
  6.         Program p = new Program();  
  7.         p.CallCallBackService();  
  8.         Console.ReadKey();  
  9.     }  
  10.     public void CallCallBackService()  
  11.     {  
  12.         InstanceContext callBack = new InstanceContext(this);  
  13.         ServiceRef.StatusServieClient client = new ServiceRef.StatusServieClient(callBack);  
  14.         client.NotifyStatus();  
  15.     }  
  16.     public void Progress(int percent)  
  17.     {  
  18.         Console.WriteLine(percent + "% Comppleted.");  
  19.     }  
  20. }  
Step 4: Run the application and the output will be same as previous sample.

The only difference is, if you want execute the duplex in a shorter time i.e., less than service timeout, we will use the second one. Otherwise the first way is recommended. The first way will not throw any exception, it is long time process.

That’s all about message exchange in WCF. If you have any questions about it please feel free to ask me. 


Similar Articles