Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of a DataContract in WCF?

Tags:

wcf

VS.net creates a template when you create a WCF project.

It adds a class to the iService1.cs file:

// Use a data contract as illustrated in the sample below to // add composite types to service operations. [DataContract] public class CompositeType {     bool boolValue = true;     string stringValue = "Hello ";      [DataMember]     public bool BoolValue     {         get { return boolValue; }         set { boolValue = value; }     }      [DataMember]     public string StringValue     {         get { return stringValue; }         set { stringValue = value; }     } } 

Since a WCF service can return any user defined class, why use a DataContract and CompositeType class?

I can return something like:

 [OperationContract] MyUserCollection GetUsers(); 

What am I missing?

like image 665
Blankman Avatar asked Nov 19 '08 19:11

Blankman


People also ask

Is DataContract mandatory in WCF?

No, the DataContractAttribute is not required - WCF will infer serialization rules.

What is DataContract and DataMember in WCF?

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.

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.

What is the use of DataMember?

Data Member are the fields or properties of your Data Contract class. You must specify [DataMember] attribute on the property or the field of your Data Contract class to identify it as a Data Member. DataContractSerializer will serialize only those members, which are annotated by [DataMemeber] attribute.


1 Answers

The DataContract is just a formal definition of a type that can be understood on both sides of the service boundary.

If you return, as in your example, a "MyUserCollection" object, the consumers of your service will need to reference the innards of your service/system, which is a violation of the SOA tenet of explicit boundaries. By using a DataContract, you are publishing the structure of your return types in a loosely-coupled way.

like image 83
Guy Starbuck Avatar answered Oct 20 '22 00:10

Guy Starbuck