Amit
Amit

Reputation: 3478

Datacontract and servicecontract difference

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.

Upvotes: 24

Views: 22233

Answers (1)

marc_s
marc_s

Reputation: 754220

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.

Upvotes: 65

Related Questions