WCF版本更新應用直接修改方法實現
大多數開發人員在使用WCF進行版本更新時,大部分都會通過繼承的方式來實現。那么,還有沒有其他更加簡便的方式呢?下面我們就為大家介紹一種直接修改原有服務和數據類型的方法來實現WCF版本更新。
WCF版本更新測試原型:
- [DataContract]
- public class Data
- {
- [DataMember]
- public int x;
- }
- [ServiceContract]
- public interface IMyService
- {
- [OperationContract]
- void Test(Data d);
- }
客戶端代理
- //------------------------------------------
- // < auto-generated>
- // 此代碼由工具生成。
- // 運行庫版本:2.0.50727.42
- //
- // 對此文件的更改可能會導致不正確的行為,并且如果
- // 重新生成代碼,這些更改將會丟失。
- // < /auto-generated>
- //-------------------------------------------
- namespace ConsoleApplication1.localhost
- {
- [GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
- [DataContractAttribute(Namespace = "...")]
- [SerializableAttribute()]
- public partial class Data : object, IExtensibleDataObject
- {
- [OptionalFieldAttribute()]
- private int xField;
- [DataMemberAttribute()]
- public int x
- {
- get
- {
- return this.xField;
- }
- set
- {
- this.xField = value;
- }
- }
- }
- [GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
- [ServiceContractAttribute(ConfigurationName =
"ConsoleApplication1.localhost.IMyService")]- public interface IMyService
- {
- [OperationContractAttribute(Action = "http://tempuri.org/IMyService/Test",
ReplyAction = "...")]- void Test(Data d);
- }
- [GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
- public interface IMyServiceChannel : IMyService, IClientChannel
- {
- }
- [DebuggerStepThroughAttribute()]
- [GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
- public partial class MyServiceClient : ClientBase< IMyService>,
IMyService- {
- public void Test(Data d)
- {
- base.Channel.Test(d);
- }
- }
- }
我們將對該服務和數據類型進行升級,添加新的成員和服務方法來實現WCF版本更新。
- [DataContract]
- public class Data
- {
- [DataMember]
- public int x;
- [DataMember]
- public int y;
- }
- [ServiceContract]
- public interface IMyService
- {
- [OperationContract]
- void Test(Data d);
- [OperationContract]
- void Test2(int x);
- }
測試結果表明,客戶端在不更新代理文件的情況下依然正常執行。看來直接通過修改進行版本更新也沒有什么問題。要是我們修改了成員的名稱會怎么樣?也沒問題,不過要使用 Name 屬性了。
- [DataContract]
- public class Data
- {
- [DataMember(Name="x")]
- public int x2;
- [DataMember]
- public int y;
- }
- [ServiceContract]
- public interface IMyService
- {
- [OperationContract]
- void Test(Data d);
- [OperationContract]
- void Test2(int x);
- }
WCF版本更新的操作提示:
1. ***為服務和相關成員特性添加 Namespace / Name 屬性。
2. 還是使用繼承方式進行版本更新要好些,避免因為意味更改造成原有客戶端無法執行。
【編輯推薦】