What are Contracts in WCF?

Contract provides Interoperability to communicate with the client. It is a type of contract between client and service. 

In WCF, we have the following types of contract.
  • Service Contract
  • Operation Contract
  • Data Contract
  • Message Contract
  • Fault Contract

Service Contract: A service contract defines the operations which are exposed by the service to the outside world. Here's an example.

  1. [ServiceContract]  
  2. interface IEmployee   
  3. {  
  4.     [OperationContract]  
  5.     EmployeeDetail GetEmployee(EmployeeInfo emp);  
  6. }  
Operation Contract: We define Operation Contract inside Service Contract.
  1. [ServiceContract]  
  2. interface IEmployee   
  3. {  
  4.     [OperationContract]  
  5.     EmployeeDetail GetEmployee(EmployeeInfo emp);  
  6. }  
Data Contract: Data Contract describes the Data to be exchanged.
  1. [DataContract]  
  2. public class EmployeeInfo  
  3. {  
  4. }  
Message Contract: Message Contract gives more control over the actual SOAP message for a service operation request or reply. A message contract defines the elements of a message (like Message Header, Message Body, etc), as well as the message-related settings, such as the level of message security.
  1. [ServiceContract]  
  2. public interface IEmployeeService   
  3. {  
  4.     [OperationContract]  
  5.     EmployeeDetail CalPrice(Employee request);  
  6. }  
  7. [MessageContract]  
  8. public class Employee  
  9. {  
  10.     [MessageHeader]  
  11.     public MyHeader SoapHeader   
  12.     {  
  13.         get;  
  14.         set;  
  15.     }  
  16.     [MessageBodyMember]  
  17.     public EmployeeInfo Employee   
  18.     {  
  19.         get;  
  20.         set;  
  21.     }  
  22. }  
  23. [DataContract]  
  24. public class MyHeader   
  25. {  
  26.     [DataMember]  
  27.     public string EmpID   
  28.     {  
  29.         get;  
  30.         set;  
  31.     }  
  32. }  
  33. [DataContract]  
  34. public class EmployeeInfo   
  35. {  
  36.     [DataMember]  
  37.     public string EMP_Name   
  38.     {  
  39.         get;  
  40.         set;  
  41.     }  
  42.     [DataMember]  
  43.     public sring Country   
  44.     {  
  45.         get;  
  46.         set;  
  47.     }  
  48.     [DataMember]  
  49.     public string City   
  50.     {  
  51.         get;  
  52.         set;  
  53.     }  
  54.     [DataMember]  
  55.     public string Mobile {  
  56.         get;  
  57.         set;  
  58.     }  
  59. }
Fault Contract: Fault Contract defines the errors raised by the service.
  1. [ServiceContract]  
  2. interface IEmpContract   
  3. {  
  4.     [FaultContract(typeof(MyFaultContract1))]  
  5.     [FaultContract(typeof(MyFaultContract2))]  
  6.     [OperationContract]  
  7.     string GetEmployeeAddress();  
  8.     [OperationContract]  
  9.     string ShowEmployee();  
  10. }