Service Contract in WCF

Service contract means the collective mechanisms by which a service's capabilities and requirements are specified for its consumers. We must say that it defines the operations that a service will perform when executed. It tells more things about a service, like message data types, operation locations, the protocols the client will need in order to communicate with the service.
 
There are three types of attributes which are used to annotate these type of operations.
  1. ServiceContractAttribute
  2. OperationContractAttribute
  3. MessageParameterAttribute.
SrvcWCF.gif 
 
ServiceContractAttribute - It is used to declare the type as a Service Contract. It can be declared without any parameters but it can also take named parameters.
  1. [ServiceContract(Name="MyService", Namespace="http://tempuri.org")]  
  2. public interface IMyService  
  3. {  
  4.   
  5.     [OperationContract]  
  6.     int AddNum(string numdesc, string assignedTo);  
  7.   
  8. }  
OperationContractAttribute - It can only be applied on methods. It is used to declare methods which belong to a Service Contract. It controls the service description and message formats.
 
MessageParameterAttribute - It controls how the names of any operation parameters and return values appear in the service description. It controls how both the parameter and return values are serialized to XML request and response elements at the transport layer. We need to use the Name property because the variable name can't be used as programming language.
  1. [OperationContract]  
  2.     [return : MessageParameter(Name="reswait")]  
  3.     string MyOp([MessageParameter(Name="string")]string s);  
Simple Program
  1. [ServiceContract]  
  2. public interface IMathOp  
  3. {  
  4.     [OperationContract]   
  5.     double AddNum(double A, double B);  
  6.    
  7.     [OperationContract]  
  8.     double Multiply (double A, double B);  
  9. }  
  10.    
  11. // Implement the IMath contract in the MathService class.  
  12. public class MathService : IMathOp  
  13. {  
  14.     public double AddNum (double A, double B) { return A + B; }  
  15.     public double Multiply (double A, double B) { return A * B; }  
  16. } 


Similar Articles