Freigeben über


Why prevent DataContract + IXmlSerializable

I left one thing unsaid in the serialization rules and Aaron's sharp eyes caught it promptly. As he mentioned in his blog, mixing interface programming model (such as IXmlSerializable or ISerializable) with DataContract programming model is disallowed in V1. Here is an example of such a class.

[DataContract]

public class XmlDataContractType : IXmlSerializable

{

    [DataMember]

    public int MyDataMember;

    //IXmlSerializable Members

}

As Aaron mentioned we could have chosen IXmlSerializable in this case. I agree that it is natural for the interface to trump attribute since it impacts the derived types as well. However, this meant that the DataContract does not impact anyone.

On the other hand, picking DataContract enables scenarios where a type is serialized with multiple serializers. Both IXmlSerializable and ISerializable are programming models that are also supported by other serializers (XmlSerializer and BinaryFormatter). A user might want to make a type IXmlSerializable or ISerializable to be used by ‘legacy’ serializers and make it a DataContract type for WCF. But this approach fails as soon as we consider inherited types. Consider two derived types of XmlDataContractType as defined below.

public class DerivedXmlType : XmlDataContractType

{

}

[DataContract]

public class DerivedDataContractType : XmlDataContractType

{

}

Class DerivedXmlType does not define DataContract but is an IXmlSerializable by virtue of inheritance. In this case IXmlSerializable projection of XmlDataContractType should be used. Since DerivedDataContractType is a DataContract it will end up using the DataContract projection of XmlDataContractType. We definitely did not want to encourage this dual projection of XmlDataContractType.

Comments

  • Anonymous
    May 23, 2006
    Yesterday a customer got in touch with me regarding some custom serialization/deserialization issues...

  • Anonymous
    September 11, 2006
    Just a quick note for everyone doing first steps in WCF service contract design.Usually you get introduced...

  • Anonymous
    July 22, 2008
    I don't understand why you don't want to encourage dual projection of XmlDataContractType. Let the developer decides. Since you can in the same entity use [DataMember]  and [XmlElement] attributes on a property you authorize actually dual projection. This is not consistent. Is there any better reason?

  • Anonymous
    September 17, 2008
    PingBack from http://underground.infovark.com/2008/09/17/dont-mix-your-serialization/