what is a service contract, operation contract and Data Contract - part 1


what is a service contract, operation contract and Data Contract? - part 1

✍: Guest


In this example we will make simple service which displays the total cost of the complete product group. In simple words this service will take three parameters per product cost, number of products and the product name. In return the service will return the total cost of all the products by multiplying number of products * cost per product. As we go ahead in this explanation we will try to understand all the terminologies which are asked in the above question.
First you need to create a Winfx service project. You can see in the below figure we have selected the Winfx project.

Figure 15.4: - Create new WinFX Service class
In this project we add a new class and name it as “serviceGetCost.cs”. This class will have our core implementation and this is the class which has all the action. The service class which has to be exposed to the external client. We need to use the ServiceContract attribute to mark it as a service class.
Service Contract attribute define saying which application interface will be exposed as a service.
You can see in the below code snippet we have made an interface and marked it as Service Contract. It’s not essential that you need to use an interface you can also use a simple class and mark it as Service but interface represent a contract and do not have implementation. In short they stand at a very higher level of abstraction. So as a good design practice using interface to represent a service contract makes more sense. The next thing to note is the OperationContract attribute.
OperationContract dictates which methods should be exposed to the external client using this service.
It defines individual exchange or request and replies. In the current sample we have defined GetTotalCost method which will be used by the end client to get the total cost results. The next thing to note in the code snippet is the DataContract attribute. In the previous two steps we have exposed class as a service by using ServiceContract and methods by using OperationContract. Every operation will definitely do some kind of data transfer.
Data Contract attributes defines which type of complex data will be exchanged between the client and the service. They determine which parameters to be serialized.
When you are using simple data types like int, bool etc it’s not necessary that you need to mark the data contract attribute. Because you will always find matching types on the client. But complex structure like one shown in the below code snippet you will need to define a data contract. Remember data contract define how this data will be passed during transmission. In short data contract attribute define how data will be serialized will transmission.

2007-11-04, 5196👍, 0💬