开发者

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 开发者_JAVA技巧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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜