Thursday, August 16, 2007

* WCF : Understanding Data Contracts (Deep Dive)

Previous Post <<-- WCF Diagnostics : Message Logging

  • Data contract is the understanding between client and service about the structure of the data which needs to be transferred between client and service in as native/simplest/standard form as possible. This removes the dependency of sharing types between client and service. e.g. in case of wsHttpBinding the data contract is in form of data types as defined by W3 Standard to make it fully interoperable.
  • Only types which are marked by attribute DataContract or DataMember are serialized. Most of the native types are by default serialization enabled.
  • Member accessibility levels (internal, private, protected, or public) do not affect the data contract.
  • The DataMemberAttribute is ignored if it is applied to static members.
  • Data Contract and Data Members can be given a name other than the type name by 'name' property.
    [DataMember(Name = "Address")]
    public string MyAddress;

  • For client and service to be able to understand each others data successfully, the data contract on both the sides should be same. Here are few requirements for equivalence of data contracts :

    • Data contracts should have same name and namespace. They need to have same data members.
    • Data members should have same name and their Data Contracts should be equivalent.
    • All names and namespaces are case sensitive.
    • Data members should be in same order. Default order is alphabetical.

  • Order of Data Member can changed using 'Order' property.
        [DataMember(Order = 1)]
    public int B;
    [DataMember(Order = 2)]
    public int A;

  • If you plan to support more than one data contract using one type, you can use 'KnownType' attribute. Using this you can support the derived contracts also.
  • For creating forward-compatible data contract, the type should implement IExtensibleDataObject which has only one property ExtensionDataObject. This ensures that data doesn't get lost when moving between old and new contract with difference of data members.
  • Adding or Removing data fields from contracts generally don't break the communication unless the members have been made mandatory. When a type with an extra field is deserialized into a type with a missing field, the extra information is ignored. When a type with a missing field is deserialized into a type with an extra field, the extra field is left at its default value, usually zero or null.

 Next Post -->> WCF : Service Instances and Sessions

No comments:

Post a Comment