Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datacontract and servicecontract difference

Tags:

wcf

As far as I knw -

ServiceContract can be used for interface/class whereas DataContract can b used only for Class, Struct and Enums

Apart from this - what are other differences b/w these 2 ? When DataContract and ServiceContract should be used in an application ?

Any sample or link would also do. Thanks in advance.

like image 518
Amit Avatar asked Jan 19 '11 05:01

Amit


People also ask

What does DataContract mean?

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts.

What is DataContract and Datamember?

A datacontract is a formal agreement between a client and service that abstractly describes the data to be exchanged. In WCF, the most common way of serialization is to make the type with the datacontract attribute and each member as datamember.

Why do we use DataContract in C#?

It is used to get or set the name for DataContract attribute of this type. It is used to get or set the order of serialization and deserialization of a member. It instructs the serialization engine that member must be present while reading or deserializing.

What is DataContract attribute?

[DataContract] attribute specifies the data, which is to serialize (in short conversion of structured data into some format like Binary, XML etc.) and deserialize(opposite of serialization) in order to exchange between the client and the Service.


1 Answers

The ServiceContract defines the service's contract - its shape and form. It defines the name of the service, its XML namespace etc., and it's typically an interface (but could also be applied to a class) that contains methods decorated with the [OperationContract] attribute - the service methods.

[ServiceContract] public interface IMyService {     [OperationContract]     Response GetData(int someKey); } 

The DataContract is a totally different beast - it decorates a class to define it as a class that's being used as a parameter or return value from one of the service methods. It's labeling that class as a "thing" to serialize onto the wire to transmit it. It's an instruction for the WCF runtime (the data contract serializer) that this class is intended to be used in a WCF service.

[DataContract] public class Response {      [DataMember]      int Key { get; set; }      [DataMember]      string ProductName { get; set; }      [DataMember]      DateTime DateOfPurchase { get; set; } } 

So the service contract and the data contract are two totally separate parts that play together to make a WCF service work - it's not like one could replace the other or something.

like image 154
marc_s Avatar answered Sep 30 '22 06:09

marc_s