What are Contracts in WCF?


A Contract is basically an agreement between the two parties i.e. Service and Client. There are two types of Contracts in WCF.

Behavioral Contracts

  • Service Contract:- Service contract describes the operation that service provide. A Service can have more than one service contract but it should have at least one Service contract. A Service Contract can be define using [ServiceContract].

Example:
[ServiceContract]
Public interface IBookOrder
{
//do some stuff
}

  • Operation Contract:- The [OperationContract] attribute declares that a method is an operation in a service contract. Only methods attributed with the [OperationContract] are exposed as service operations.

Example:
[OperationContract]
bool CheckOrder(int ordernumber);

  • Fault Contract:- It is used to communicate error information from a service to a client.

Structural Contracts

  • Data Contract:- A data contract describes the data that is to be exchanged between client and service. The service and the client do not need to agree on the types, but they do need to agree on the data contract.

Example:

[DataContract]
Public class BuyStock
{

}

  • Message Contract:- Message contracts provide the ultimate control over the formatting of the SOAP messages. A message contract provides the level of interoperability you would need when you need to communicate with clients or other systems.

Example:
[MessageContract]
Public class BuyStock
{
[MessageHeader]
Public string Title;
[MessageBodyMember]
Public decimal Cost;
}