开发者

What are the advantages of using [DataContract] rather than [Serializable] in WCF

开发者 https://www.devze.com 2023-02-06 20:09 出处:网络
Any advantage to using DataContr开发者_开发问答act?See a great comparison of XmlSerializer and DataContractSerializer on Dan Rigsby\'s blog.

Any advantage to using DataContr开发者_开发问答act?


See a great comparison of XmlSerializer and DataContractSerializer on Dan Rigsby's blog.

Some points in favor of DataContractSerializer:

  • about 10% faster than XmlSerializer
  • will serialize anything decorated with a [DataMember] - even if it's not public visible
  • will not serialize anything unless you specifically tell it to ("opt-in")
  • you can define the order in which the elements are serialized using the Order= attribute on the [DataMember]
  • doesn't require a parameterless constructor for deserialization


There is one question that hasn't been answered yet by the others here: What if you use [Serializable], but still use DataContractSerializer to serialize that type? Is it any different from serializing a [DataContract] type with DataContractSerializer?

The answer: it makes absolutely no difference! The reason is that when you pass in any supported type to DataContractSerializer, on the first serialization or deserialization episode, it "shreds" the type to an internal structure that contains all the information about the type's members etc. It then uses the cached internal structure (preserved using dynamic IL) for subsequent serialization episodes, never going back to the original type.

Also, if you're comparing DataContractSerializer's serialization of [Serializable] types vs. XmlSerializer's serialization of those same types, you will find DataContract's serialization to be exponentially faster. A little bit of this is visible in the performance comparison whitepaper available here: http://msdn.microsoft.com/en-us/library/bb310550.aspx


You can also keep in mind that the DataContract is more consumer-oriented than XmlSerializer.

While the XmlSerializer has a pure technical dimension ("how do I transform this object into XML"), the DataContract is the public-facing representation of a business concept.

As such the DataContract acts as a reminder that every change you make to your class will have an impact on consumers and that you are implicitly bound by this contract. Conceptually, the DataContract is a central element of your service architecture, XmlSerializer is just a helper.


There is no real base for comparison if all you do is serialize to and deserialize from XML, apart from syntactical differences and minor features. The most powerful advantage of DataContract over Serializable - something which everyone seems to skip over - is that data contracts are not XML specific.

Working with data contracts, there are only two logical constructs: data contracts and data members (members of a data contract). There are no such things in a data contract as "elements", or "xml elements".

In theory, data contract based serialization enables an object structure to be represented in any data exchange format, although AFAIK only XML and JSON serialization/deserialization are available in the .NET framework at the moment. However, it is certainly possible to create a serializer than operates with, say, RDF, and I suspect there are additional serializers out there.

Consider the below simple architecture:

C#

[DataContract]
class Company
{
    [DataMember]
    public string Name { get; set }

    [DataMember]
    public Person[] People { get; set }
}

[DataContract]
class Person
{
    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }
}

This contract is not XML specific. You didn't specify anything XML-related. You can serialize an instance of the above architecture either into XML:

XML

<Company>
  <Name>...</Name>
  <People>
    <Person>
      <FirstName>James</FirstName>
      <LastName>Sunderland</LastName>
    </Person>
    ...
  </People>
</Company>

... or into JSON:

JSON

{
    "Company": {
        "Name": "...",
        "People": [
            {
                "FirstName": "James",
                "LastName": "Sunderland"
            },
            ...
        ]
    }
}

... or into any arbitrary data exchange format, as long as you are in possession of a serializer for that format.

This is very powerful and flexible, especially if you have a webservice that is consumed by multiple types of clients and peers, or if the consumer group of your webservice is subject to expansion in the future:

  • JSON is easier to serialize/deserialize in JavaScript and PHP servers (or any dynamic language),
  • XML is more straightforward to serialize/deserialize in WCF clients.

If you don't want to constrain yourself to XML as the only data exchange format in your application architecture, I recommend you go with DataContract. Otherwise, Serializable is slightly more useful for XML only.


Key issues with XmlSerializer to serialize .NET types to XML

  • Only Public fields or Properties of .NET types can be translated into XML
  • Only the classes which implement IEnumerable interface
  • Classes that implement the IDictionary interface, such as Hash table cannot be serialized Important difference between DataContractSerializer and XMLSerializer

A practical benefit of the design of the DataContractSerializer is better performance over Xmlserializer.

  • XML Serialization does not indicate which fields or properties of the type are serialized into XML whereas DataCotractSerializer
  • Explicitly shows the which fields or properties are serialized into XML
  • The DataContractSerializer can translate the HashTable into XML


Although this question is quite old but I will summarize my understanding :

1) Datacontract gives you the flexibility of serializing certain members or fields using (DataMember) attribute. 2) You can decide with DataContract the order in which your objects will be serialized.

Apart from the obvious things as DataContract serializes your public members whereas Serializable will by default serialize your fields present.

0

精彩评论

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

关注公众号