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.
- [ServiceContract]
- interface IEmployee
- {
- [OperationContract]
- EmployeeDetail GetEmployee(EmployeeInfo emp);
- }
Operation Contract: We define Operation Contract inside Service Contract.
- [ServiceContract]
- interface IEmployee
- {
- [OperationContract]
- EmployeeDetail GetEmployee(EmployeeInfo emp);
- }
Data Contract: Data Contract describes the Data to be exchanged.
- [DataContract]
- public class EmployeeInfo
- {
- }
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.
- [ServiceContract]
- public interface IEmployeeService
- {
- [OperationContract]
- EmployeeDetail CalPrice(Employee request);
- }
- [MessageContract]
- public class Employee
- {
- [MessageHeader]
- public MyHeader SoapHeader
- {
- get;
- set;
- }
- [MessageBodyMember]
- public EmployeeInfo Employee
- {
- get;
- set;
- }
- }
- [DataContract]
- public class MyHeader
- {
- [DataMember]
- public string EmpID
- {
- get;
- set;
- }
- }
- [DataContract]
- public class EmployeeInfo
- {
- [DataMember]
- public string EMP_Name
- {
- get;
- set;
- }
- [DataMember]
- public sring Country
- {
- get;
- set;
- }
- [DataMember]
- public string City
- {
- get;
- set;
- }
- [DataMember]
- public string Mobile {
- get;
- set;
- }
- }
Fault Contract: Fault Contract defines the errors raised by the service.
- [ServiceContract]
- interface IEmpContract
- {
- [FaultContract(typeof(MyFaultContract1))]
- [FaultContract(typeof(MyFaultContract2))]
- [OperationContract]
- string GetEmployeeAddress();
- [OperationContract]
- string ShowEmployee();
- }