In this tutorial, we are going to understand What is WCF Contract and different types of WCF Contract? WCF Contract provides the compatibility that the service and the client need to communicate with each other.
What is WCF Contract?
WCF defines contracts which provide the compatibility that the service and the client need to communicate with each other. It is a standard way of defining what a service does. The contract also defines what protocol it will use, how communication will be done and what type of message exchange format to use etc.
There are four types of Contract WCF uses.
Service Contract describes is the interface for the service that describes the operation or method for outside the world.
A [ServiceContract] attribute is used to define Service. A Service must have at least one Service Contract and can have multiple Service Contract.
An Example of Service Contract.
An Operation Contract describes the method or Operation in Service Contract. It defines the parameter and returns type of the Operation. An Operation Contract describes the functionality that will expose to the client such as Inserting a new record to the database or fetching records from the database.
[OperationContract] attribute is used to define an Operation Contract.
An example of Operation Contract in Service Contract is:
Data Contract describes the Data that need to be exchanged between Client and Service. It is actually nothing but get set property that describes data type for your information. The Data Contract can be used by Operation Contract as a parameter or as a return type.
There are two types of Data Contract such as:
Data Contract: This attribute is used to define a Class.
Data Member: This attribute is used to define properties inside the class.
The default message pattern that the WCF runtime uses is SOAP. Most of the time we focus on developing Data Contract. But sometimes we also need to customize SOAP message format. It that case WCF provided us Message Contract.
A Message Contract is used to define element like Message Header, Message Body. Message Contract is used to send or retrieve information in SOAP header.
A Message Contract can be defined as:
Fault Contract is responsible for handling the Errors or Exceptions raised by the service. A Fault Contract defines how the WCF Service handles the error and serves the error to the client. In the managed application, we handle the error or exception using try and catch block but in WCF service but these exceptions are technology specific.
An example of using Fault Contract:
Hope you understand the WCF Contract and different types of Contracts that WCF uses. I would like to have your Feedback, Comments and Suggestions.