Service Contract and Service Proxy

Service Contract

A contract is a specification of the way a consumer of a service will interact with the provider of the service. It specifies the format of the request and response from the service. A service contract may require a set of preconditions and post conditions. The preconditions and post conditions specify the state that the service must be in to execute a particular function. The contract may also specify quality of service (QoS) levels. QoS levels are specifications for the nonfunctional aspects of the service.

Service Contract can be defined using ServiceContract and OperationContract attribute. ServiceContract attribute is similar to the WebServcie attribute in the WebService and [OpeartionContract] is similar to the [WebMethod] in WebService.

It describes the client-callable operations (functions) exposed by the service. It maps the interface and methods of your service to a platform-independent description
It describes message exchange patterns that the service can have with another party. Some service operations might be one-way; others might require a request-reply pattern. It is analogous to the element in WSDL
To create a service contract you define an interface with related methods representative of a collection of service operations, and then decorate the interface with the ServiceContract Attribute to indicate it is a service contract. Methods in the interface that should be included in the service contract are decorated with the OperationContract Attribute.

[ServiceContract()]
public interface ISimpleCalculator
{
[OperationContract()]
int Add(int num1, int num2);
}

Once we define Service contract in the interface, we can create implement class for this interface.

public  class SimpleCalculator : ISimpleCalculator
{
public int Add(int num1, int num2)
{
return num1 + num2;
}
}

With out creating the interface, we can also directly created the service by placing Contract in the implemented class. But it is not good practice of creating the service

 [ServiceContract()]
 public class SimpleCalculator
 {
 [OperationContract()]
 public int Add(int num1, int num2)
 {
 return num1 + num2;
 }
 }

Service Proxy

The service provider supplies a service proxy to the service consumer. The service consumer executes the request by calling an API function on the proxy. The service proxy, shown in below diagram  finds a contract and a reference to the service provider in the registry. It then formats the request message and executes the request on behalf of the consumer. The service proxy is a convenience entity for the service consumer. It is not required; the service consumer developer could write the necessary software for accessing the service directly

Service Proxy