Adding field to WCF data contract breaks clients?

后端 未结 2 1649
时光取名叫无心
时光取名叫无心 2020-12-14 09:36

I have a WCF service that returns a class that implements IExtensibleDataObject. I need to add a new field to this class. I updated the DataContract interface and made the

相关标签:
2条回答
  • 2020-12-14 10:23

    It depends on how you have set up your data contract.

    In WCF, using all the defaults, your service will use the DataContractSerializer (DCS) to serialize your object into XML. The DCS will serialize your fields in order - first the public ones, then the private ones. Within each visibility group, it will order the fields/properties alphabetically by name.

    Thus, if you introduce a new public property MiddleName and you already had FirstName and LastName, you would be fine: the old XML would have been

    <YourObject>
       ....
       <FirstName>.....</FirstName>
       <LastName>.....</LastName>
    </YourObject>
    

    and your new one would just simply add a new property at the end:

    <YourObject>
       ....
       <FirstName>.....</FirstName>
       <LastName>.....</LastName>
       <MiddleName>....</MiddleName>
    </YourObject>
    

    Such an update "add something at the end" should work just fine, the DCS will just simply ignore additional tags in the XML.

    However: had you introduced a property called Gender, that would be stuck between <FirstName> and <LastName> and would thus break the order of the data in your XML and thus would break the data contract - no "old" client will be able to call your new service.

    In order to take control of this, you can put specific Order= attributes on your data members in your data contract:

    [DataContract]
    public class SomeAddress
    {
       [DataMember(Order=0)]
       public string FirstName;
    
       [DataMember(Order=1)]
       public string LastName;
    }
    

    Then you could easily add a new property - just add it to the end of the list!

    [DataContract]
    public class SomeAddress
    {
       [DataMember(Order=0)]
       public string FirstName;
    
       [DataMember(Order=1)]
       public string LastName;
    
       [DataMember(Order=2)]
       public string Gender;
    }
    

    So by using the Order= attribute on your data contracts, you can take control of your XML layout, and you can make simple extensions of existing data contracts non-breaking updates.

    For more background and in-depth know-how, you ought to read Serialization in Windows Communication Foundation on MSDN Magazine's web site - highly recommended.

    0 讨论(0)
  • 2020-12-14 10:28

    From your service reference context menu choose... "Update Service Reference"

    0 讨论(0)
提交回复
热议问题