WCF - Message Types
Traditionally, in any type of application, we can create a method that does some task. When creating it, we can consume it in the same application to even reference the class in which it is contained and also consume them in various projects. To make a call to this method, we should expect its implementation and, when completed, we continue in the program. When creating an operation in a WCF service, it also behaves the same way. But this is not the only alternative provided by WCF. Disregarding the possibility of asynchronous calls , we have three alternatives that we can use to build an operation (method) of a service: request-reply , one-way and duplex (callbacks) . The focus of this paper is to explore such alternatives and how they influence the configuration and deployment and execution of service. Request-Reply When creating a method that returns some information within an interface that will be the contract of service, we can decorate this method with the attributeOperationContractAttribute , which will tell the runtime WCF it should be published, and consequently consumed by customers who referenciarem service. With this basic configuration, the method is already based on the standard request-reply . As its name says, invoking the method from a client, a message is sent to the service through the proxy , containing the necessary information for the implementation of method. At this time the message travels through the network until the related service; to reach the other side, the dispatcher opens the message and effectively runs the requirido method. On completion of the same, a new message is generated and returned as a return to the same client that requested. Upon reaching the other side (client), the proxy opens the message, capture the result (or error) and returns to the application. Throughout the execution of the method, the client application is blocked until the result not back yet or when the timeout is reached. Except for the bindings NetPeerTcpBinding and NetMsmqBinding all support type operations request-reply . For a better understanding the image below illustrates the process between the client and the service when a standard method based on therequest-reply runs:
![]() |
Figure 1 - Model Request-Reply . |
When you have operations that do not return values, and especially the client is not interested in the success or failure of the same, we can use the technique called one-way . Also known as fire-and-forget , it allows the proxyto send the message to its destination without waiting for the execution. There is a minimum block client-side, which is only required for the proxy to send the message and service to Line up. From there, the client is free to continue in the program. As the feature since the message type is not notify the client of success or failure, any exception that occurs during the execution of the method will not notify the client (with some exceptions we will see below). In this case, we can use some features provided by the binding being used, such as using reliable sessions or even the possibility of creating a contract callback operations along with duplex we will see later in this article yet. Through the image below, we can see the message traveling between client and server, with no one correlated response message:
![]() |
Figure 2 - Model One-Way . |
using System;
using System.ServiceModel;
[ServiceContract]
public interface ICliente
{
[OperationContract (IsOneWay = true)]
void Notify (string email);
}
|
![]() |
Figure 3 - Model Duplex (callbacks) . |
![]() |
Figure 4 - Operation WSDualHttpBinding . |
using System;
using System.ServiceModel;
public interface ICallback
{
[OperationContract]
NotificacaoRealizada void (string msg);
}
|
using System;
using System.ServiceModel;
[ServiceContract (CallbackContract = typeof (ICallback))]
public interface ICliente
{
[OperationContract]
void Notify (string email);
}
|
using System;
using System.ServiceModel;
[ServiceBehavior (InstanceContextMode = InstanceContextMode.PerCall
, ConcurrencyMode = ConcurrencyMode.Reentrant)]
public class ServicoDeClientes: ICliente
{
public void Notify (string email)
{
houveProblemas bool = false;
try
{
// Makes the notification
}
catch
{
houveProblemas = true;
}
finally
{
ICallback callback =
OperationContext.Current.GetCallbackChannel <ICallback> ();
string msg =
houveProblemas?
"There were problems in the notification." :
"Notification successful.";
if (callback! = null)
callback.NotificacaoRealizada (msg);
}
}
}
|
using System;
using System.ServiceModel;
using (ClienteClient proxy =
new ClienteClient (new InstanceContext (new GerenciadorDeRetorno ())))
{
proxy.Notificar ("israel@projetando.net");
Console.ReadLine ();
}
// ....
public class GerenciadorDeRetorno: IClienteCallback
{
public void NotificacaoRealizada (string msg)
{
Console.WriteLine (msg);
}
}
|
One-Way
The creation of the contract to support this type of message changes slightly from the traditional format and allbindings support this type of message. Since the idea of the operations of type one way is no return, the methods should return nothing, or should be void . Any kind of data you put it in different operations marked as one-way , an exception will be thrown like XXXXX. As the pattern is request-reply to say that the WCF operation it is an operation one way , we should set the property IsOneWay , provided by the attribute OperationContractAttributeas True . The following code snippet illustrates this configuration:
If an error occurs during the execution of the service and the same is set to PerCall (which is stateless / session) and exposed via BasicHttpBinding or WSHttpBinding (without security options and enabled reliable messaging), the proxy client will not be affected and, consequently, can make subsequent requests; Now, if you are being exposed through the WSHttpBinding with security, NetTcpBinding without the option of reliable messaging enabled or by binding NetNamedPipeBinding and an exception occurs during the processing of the transaction, it will affect the proxy client side, and he can no longer perform Operations from this same proxy , and closing the same will not occur safely. Finally, if the latter bindings are enabled with the option of reliable messaging, he can continue using the same proxy , even when an exception occurs. When the service is exposed in the modelPerSession or Single supporting session gets a little more difficult to have a control under the exceptions that are raised. If the service is exposed via NetTcpBinding or NetNamedPipeBinding and an error occurs, the session is closed, the service instance will be destroyed and the proxy client will be affected and there were no subsequent calls. Duplex (Callbacks) The third and last alternative we have WCF is the ability to make callbacks . The purpose of this technique is to allow a bidirectional communication, or call the customer service of a method and a service invoking a method on the client. This type of communication allows, in most cases, a particular service to notify the client that some event occurred, giving him a chance to get to interact with a specific client or even multiple clients through a publisher-subscriber system. The image below illustrates the operation of this type of message:
Not all bindings enable this type of communication. The NetTcpBinding bindings and NetNamedPipeBinding do this natively, due to the nature of the protocols used. The HTTP protocol does not provide this support, because it is a connection that does not maintain the connection between client and server. To enable the callback function from HTTP, one was created binding called WSDualHttpBinding that has this purpose. When we useWSDualHttpBinding , WCF uses a different channel to invoke the callback . Internally, what ends up being done on the client side - by the runtime WCF - is the creation of an "endpoint" (including an available port) for which the related service can invoke it. This temporary address that is registered under the WCF Http.sys which is a component of low-level and part of the Windows Communication system. Therefore, any request to get to this"endpoint" , the Http.sys forward to the runtime WCF that will ultimately trigger the class that implements theinterface of callback (more details below) which, in turn, was provided by the service agreement. The image below illustrates how communication is performed between server and client from WSDualHttpBinding :
To implement this type of communication, and define the interface that will serve as the contract of service, we need to also create a second interface that specifies the callback (this is also called a contract callback ). Thisinterface will contain the method to be implemented by the client and the WCF will trigger when you feel necessary. Unlike an interface contract, the interface of callback methods only decorates with the attributeOperationContractAttribute . The code below illustrates how to proceed to create it:
Despite the operations callback does not require that they are one-way , it is good practice because it decreases the possibility of deadlocks . After the contract callback is defined, we need to associate it with the service contract. For this, there is a property called CallbackContract provided by the attribute ServiceContractAttribute , expecting a type Type , specifying the contract callback . Once the associated callback to the service contract, the WSDL will contemplate it, allowing the customer to implement the callback and inform you when creating theproxy . The code below illustrates this association:
Does the assignment will determine when to invoke the callback . To make this possible, we must first obtain the channel of communication between the service and the client and, therefore, resort to class OperationContext . It provides a generic method called GetCallbackChannel which returns the instance of the channel between the service and the client. If the return is not null, then it means that the client has implemented (and interest) bycallback . From now on, when you find it convenient, you can invoke the method callback that will be triggered on the client. The example below shows how to invoke the callback :
As stated earlier, the callback will be contemplated in WSDL, and as the contract of service, the interface that represents the callback will also be made available for the implementation of the client side. This interface must be implemented in a class by placing the desired inside the method (s) (s) provided (s) the code interface forcallback . Implemented with the class, you should inform them in creation (constructor) of the proxy . This new version of the constructor proxy accepts an instance of the class InstanceContext . This class involves and manages the class instance where the interface of callback was implemented. At this point, the runtime WCF will be monitoring so that when the callback is triggered, the proxy is notified and, therefore, invoke its method from the client side. The code illustrates this configuration:
When a callback is part of the contract, the class instance InstanceContext will be mandatory in either versions (overloads ) the proxy . Another important point is related to the lifetime of the proxy for when the callbackhappens, he should still be active to be able to receive the notification sent by the service. Important Note:When you allows callbacks to be triggered by their service, it is important if you watch the synchronization model used the same because otherwise, you could face problems of deadlocks . If you want to learn more about management modes of competition within the WCF, and especially on how Reentrant , may resort to this article .Conclusions: The article showed the three possible features that an operation can be developed in WCF. Each has a unique purpose which, although adopted, can bring great improvement in performance and also enable greater interactivity between client and service. Finally, it is important to also say that when the client mentioned in this article can also be referring to another service, something that is quite possible.
Comments
Post a Comment