When DataContract and ServiceContract should be used in an application ?

Technology CommunityCategory: WCFWhen DataContract and ServiceContract should be used in an application ?
VietMX Staff asked 3 years ago

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.