一、引言
在上一篇博文中,我們創建了一個簡單WCF應用程序,在其中介紹到WCF最重要的概念又是終結點,而終結點又是由ABC組成的。對於Address地址也就是告訴客戶端WCF服務所在的位置,而Contract又是終結點中比較重要的一個內容,在WCF中,契約包括服務契約、數據契約、消息契約和錯誤契約,在本篇博文將解析下數據契約的內容,關於其他三種契約將會后面的博文中陸續介紹。
二、引出問題——WCF操作重載限制
C#語言是支持操作重載的,然而在WCF實現操作重載有一定的限制。錯誤的操作重載實例:
1 [ServiceContract(Name = "HellworldService", Namespace = "http://www.Learninghard.com")] 2 public interface IHelloWorld 3 { 4 [OperationContract] 5 string GetHelloWorld(); 6 7 [OperationContract] 8 string GetHelloWorld(string name); 9 }
如果你像上面一樣來實現操作重載的話,在開啟服務的時候,你將收到如下圖所示的異常信息:
然而,為什么WCF不允許定義兩個相同的操作名稱呢?原因很簡單,因為WCF的實現是基於XML的,它是通過WSDL來進行描述,而WSDL也是一段XML。在WSDL中,WCF的一個方法對應一個操作(operation)標簽。我們可以參考下面一段XML,它是從一個WCF的WSDL中截取下來的。
<wsdl:import namespace="http://www.Learninghard.com" location="http://localhost:9999/GetHelloWorldService?wsdl=wsdl0"/> <wsdl:types/> <wsdl:binding name="BasicHttpBinding_HellworldService" type="i0:HellworldService"> <soap:binding transport="http://schemas.xmlsoap.org/soap/http"/> <wsdl:operation name="GetHelloWorldWithoutParam"> <soap:operation soapAction="http://www.Learninghard.com/HellworldService/GetHelloWorldWithoutParam" style="document"/> <wsdl:input> <soap:body use="literal"/> </wsdl:input> <wsdl:output> <soap:body use="literal"/> </wsdl:output> </wsdl:operation> <wsdl:operation name="GetHelloWorldWithParam"> <soap:operation soapAction="http://www.Learninghard.com/HellworldService/GetHelloWorldWithParam" style="document"/> <wsdl:input> <soap:body use="literal"/> </wsdl:input> <wsdl:output> <soap:body use="literal"/> </wsdl:output> </wsdl:operation> </wsdl:binding> <wsdl:service name="HelloWorldService"> <wsdl:port name="BasicHttpBinding_HellworldService" binding="tns:BasicHttpBinding_HellworldService"> <soap:address location="http://localhost:9999/GetHelloWorldService"/> </wsdl:port> </wsdl:service>
從上面的代碼可以看出,每個Operation由一個operation XML Element表示,而每個Operation還應該具有一個能夠唯一表示該Operation的ID,這個ID則是通過name屬性來定義。Operation元素的Name屬性通常使用方法名來定義,所以,如果WCF服務契約中,包含兩個相同的操作方法名時,此時就違背了WSDL的規定,這也是WCF不可以使用操作重載的原因。
三、解決問題——WCF中實現操作重載
既然,找到了WCF中不能使用操作重載的原因(即必須保證Operation元素的Name屬性唯一),此時,要想實現操作重載,則有兩種思路:一是兩個不同的操作名,二是實現一種Mapping機制,使得服務契約中的方法名映射到一個其他的方法名,從而來保證Name屬性的唯一。對於這兩種解決思路,第一種顯然行不通,因為,方法名不同顯然就不叫操作重載了,所以,我們可以從第二種解決思路下手。值得慶幸的是,這種解決思路,微軟在實現WCF的時候已經幫我們實現好了,我們可以通過OperationContractAttribute的Name屬性來為每個操作方法名定義一個別人,而生成的WSDL將使用這個別名來作為Operation元素的Name屬性,所以我們只需要為兩個相同方法名定義兩個不同的別名就可以解決操作重載的問題了。既然有了思路,下面就看看具體的實現代碼吧。具體服務契約的實現方法如下所示:
1 namespace Contract 2 { 3 [ServiceContract(Name = "HellworldService", Namespace = "http://www.Learninghard.com")] 4 public interface IHelloWorld 5 { 6 [OperationContract(Name = "GetHelloWorldWithoutParam")] 7 string GetHelloWorld(); 8 9 [OperationContract(Name = "GetHelloWorldWithParam")] 10 string GetHelloWorld(string name); 11 } 12 }
經過上面的步驟也就解決了在WCF中實現操作重載的問題。接下來讓我們來完成一個完整的操作重載的例子。
定義契約完成之后,那就接着來實現下服務契約,具體的實現服務契約代碼如下所示:
namespace Services { public class HelloWorldService : IHelloWorld { public string GetHelloWorld() { return "Hello World"; } public string GetHelloWorld(string name) { return "Hello " + name; } } }
接着,來繼續為這個WCF服務提供一個宿主環境,這里先以控制台應用程序來實現宿主應用程序,具體的實現代碼和配置代碼如下所示:
namespace WCFServiceHostByConsoleApp { class Program { static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(Services.HelloWorldService))) { host.Opened += delegate { Console.WriteLine("服務已開啟,按任意鍵繼續...."); }; host.Open(); Console.ReadLine(); } } } }
對應的服務端配置文件如下所示:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="HelloWorldSerBehavior"> <serviceMetadata httpGetEnabled="True" httpGetUrl="http://localhost:9999/GetHelloWorldService"/> </behavior> </serviceBehaviors> </behaviors> <services> <service name ="Services.HelloWorldService" behaviorConfiguration="HelloWorldSerBehavior"> <endpoint address="http://localhost:9999/GetHelloWorldService" binding="basicHttpBinding" contract="Contract.IHelloWorld"/> </service> </services> </system.serviceModel> </configuration>
接着,我們來創建一個客戶端通過代理對象來調用WCF服務方法。首先以管理員運行WCFServiceHostByConsoleApp.exe文件來開啟服務,WCF服務開啟成功后,在對應的客戶端右鍵添加服務引用,在打開的添加服務引用窗口中輸入WCF服務地址:http://localhost:9999/GetHelloWorldService,點確定按鈕來添加服務引用,添加成功后,VS中集成的代碼生成工具會幫我們生成對應的代理類。接下來,我們可以通過創建一個代理對象來對WCF進行訪問。具體客戶端的實現代碼如下所示:
1 namespace Client3 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 using (HellworldServiceClient helloWorldProxy = new HellworldServiceClient()) 8 { 9 Console.WriteLine("服務返回的結果是: {0}", helloWorldProxy.GetHelloWorldWithoutParam()); 10 Console.WriteLine("服務返回的結果是: {0}", helloWorldProxy.GetHelloWorldWithParam("Learning Hard")); 11 } 12 13 Console.ReadLine(); 14 } 15 } 16 }
這樣,你運行客戶端程序時(注意不要關閉WCF服務宿主程序),你將看到如下圖所示的運行結果。
在上面客戶端的實現代碼中,從客戶端的角度來看,我們並不知道我們是對重載方法進行調用,因為我們調用的明明是兩個不同的方法名,這顯然還不是我們最終想要達到的效果,此時,有兩種方式來達到客戶端通過相同方法名來調用。
- 第一種方式就是手動修改生成的服務代理類和服務契約代碼,使其支持操作重載,修改后的服務代理和服務契約代碼如下所示:

namespace Client3.ServiceReference { [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ServiceModel.ServiceContractAttribute(Namespace="http://www.Learninghard.com", ConfigurationName="ServiceReference.HellworldService")] public interface HellworldService { // 把自動生成的方法名GetHelloWorldWithoutParam修改成GetHelloWorld [System.ServiceModel.OperationContractAttribute(Name = "GetHelloWorldWithoutParam", Action = "http://www.Learninghard.com/HellworldService/GetHelloWorldWithoutParam", ReplyAction = "http://www.Learninghard.com/HellworldService/GetHelloWorldWithoutParamResponse")] string GetHelloWorld(); // // 把自動生成的方法名GetHelloWorldWithoutParamAsync修改成GetHelloWorldAsync [System.ServiceModel.OperationContractAttribute(Name = "GetHelloWorldWithoutParam", Action="http://www.Learninghard.com/HellworldService/GetHelloWorldWithoutParam", ReplyAction="http://www.Learninghard.com/HellworldService/GetHelloWorldWithoutParamResponse")] System.Threading.Tasks.Task<string> GetHelloWorldAsync(); [System.ServiceModel.OperationContractAttribute(Name = "GetHelloWorldWithParam", Action="http://www.Learninghard.com/HellworldService/GetHelloWorldWithParam", ReplyAction="http://www.Learninghard.com/HellworldService/GetHelloWorldWithParamResponse")] string GetHelloWorld(string name); [System.ServiceModel.OperationContractAttribute(Name = "GetHelloWorldWithParam", Action = "http://www.Learninghard.com/HellworldService/GetHelloWorldWithParam", ReplyAction = "http://www.Learninghard.com/HellworldService/GetHelloWorldWithParamResponse")] System.Threading.Tasks.Task<string> GetHelloWorldAsync(string name); } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public interface HellworldServiceChannel : Client3.ServiceReference.HellworldService, System.ServiceModel.IClientChannel { } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public partial class HellworldServiceClient : System.ServiceModel.ClientBase<Client3.ServiceReference.HellworldService>, Client3.ServiceReference.HellworldService { public HellworldServiceClient() { } public HellworldServiceClient(string endpointConfigurationName) : base(endpointConfigurationName) { } public HellworldServiceClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public HellworldServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public HellworldServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } public string GetHelloWorld() { return base.Channel.GetHelloWorld(); } public System.Threading.Tasks.Task<string> GetHelloWorldAsync() { return base.Channel.GetHelloWorldAsync(); } public string GetHelloWorld(string name) { return base.Channel.GetHelloWorld(name); } public System.Threading.Tasks.Task<string> GetHelloWorldAsync(string name) { return base.Channel.GetHelloWorldAsync(name); } } }
此時,客戶端的實現代碼如下所示:
class Program { static void Main(string[] args) { using (HellworldServiceClient helloWorldProxy = new HellworldServiceClient()) { Console.WriteLine("服務返回的結果是: {0}", helloWorldProxy.GetHelloWorld()); Console.WriteLine("服務返回的結果是: {0}", helloWorldProxy.GetHelloWorld("Learning Hard")); } Console.ReadLine(); } }
此時,客戶端運行后的運行結果與上面的運行結果一樣,這里就不貼圖了。
- 第二種方式就是自己實現客戶端代理類,而不是由VS代碼生成工具。具體重新的proxy Class的實現代碼代碼如下所示:
1 using Contract; 2 using System.ServiceModel; 3 namespace Client2 4 { 5 class HellworldServiceClient : ClientBase<IHelloWorld>, IHelloWorld 6 { 7 #region IHelloWorld Members 8 public string GetHelloWorld() 9 { 10 return this.Channel.GetHelloWorld(); 11 } 12 13 public string GetHelloWorld(string name) 14 { 15 return this.Channel.GetHelloWorld(name); 16 } 17 #endregion 18 } 19 }
此時客戶端的實現代碼和配置文件如下所示:

namespace Client2 { class Program { static void Main(string[] args) { using (var proxy = new HellworldServiceClient()) { // 通過自定義代理類來調用進行服務方法的訪問 Console.WriteLine("服務返回的結果是: {0}", proxy.GetHelloWorld()); Console.WriteLine("服務返回的結果是: {0}", proxy.GetHelloWorld("Learning Hard")); } Console.Read(); } } }
對應的配置文件如下所示:

<configuration> <system.serviceModel> <client> <endpoint address="http://localhost:9999/GetHelloWorldService" binding ="basicHttpBinding" contract ="Contract.IHelloWorld"/> </client> </system.serviceModel> </configuration>
四、利用Windows Service來寄宿WCF服務
在上一篇博文中,我們介紹了把WCF寄宿在控制台應用程序和IIS中,而WCF服務可以寄宿在任何應用程序中,如WPF、WinForms和Windows Services。這里再實現下如何在Windows Services中寄宿WCF服務。下面一步步來實現該目的。
- 第一步:創建Windows 服務項目,具體添加步驟為右鍵解決方案->添加->新建項目,在已安裝模板中選擇Windows 服務模板,具體如下圖示所示:
- 第二步:添加Windows服務之后,你將看到如下圖所示的目錄結構。
然后修改對應的Service1.cs文件,使其實現如下代碼所示:
1 // 修改類名 2 public partial class WindowsService : ServiceBase 3 { 4 public WindowsService() 5 { 6 InitializeComponent(); 7 } 8 9 public ServiceHost serviceHost = null; 10 11 // 啟動Windows服務 12 protected override void OnStart(string[] args) 13 { 14 if (serviceHost != null) 15 { 16 serviceHost.Close(); 17 } 18 19 serviceHost = new ServiceHost(typeof(Services.HelloWorldService)); 20 serviceHost.Open(); 21 } 22 23 // 停止Windows服務 24 protected override void OnStop() 25 { 26 if (serviceHost != null) 27 { 28 serviceHost.Close(); 29 serviceHost = null; 30 } 31 } 32 }
對應的配置文件代碼如下所示:
<system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="WindowsServiceBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors> <services> <service name="Services.HelloWorldService" behaviorConfiguration="WindowsServiceBehavior"> <endpoint address="" binding="wsHttpBinding" bindingConfiguration="" name="WindowsService" contract="Contract.IHelloWorld" /> <host> <baseAddresses> <add baseAddress="http://localhost:8888/WCFServiceHostByWindowsService"/> </baseAddresses> </host> </service> </services> </system.serviceModel>
- 第三步:在WindowsService的設計界面,右鍵選擇添加安裝程序,具體操作如下圖所示。
添加安裝程序之后,會多出一個ProjectInstaller.cs文件,然后在其設計頁面修改ServiceProcessInstaller和ServiceInstaller對象屬性,具體設置的值如下圖所示:
經過上面的步驟,程序的代碼就都已經全部實現了,接下來要做的是安裝Windows 服務和啟動Windows服務。
首先是安裝Windows服務:以管理員身份運行VS2012開發命令提示,進入項目的對應的exe所在的文件夾,這里的指的是WindowsServiceHost.exe所在的文件夾,然后運行 “installutil WindowsServiceHost.exe”命令,命令運行成功后,你將看到如下所示的運行結果:
安裝成功之后,你可以運行 “net start HelloWorldServiceHost” 命令來啟動服務。因為開始設置服務的名稱是HelloWorldServiceHost。你也可以通過Services中來手動啟動服務,啟動成功之后,你將在服務窗口看到啟動的服務。具體效果如下圖所示。
服務啟動后,在客戶端中同樣是添加服務引用的方式來添加服務引用,在添加服務引用窗口輸入地址:http://localhost:8888/WCFServiceHostByWindowsService。點擊確定按鈕。添加服務引用成功后,對應的客戶端調用代碼如下所示:

1 namespace Client 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 using (var proxy = new HellworldServiceClient()) 8 { 9 // 通過代理類來調用進行服務方法的訪問 10 Console.WriteLine("服務返回的結果是: {0}", proxy.GetHelloWorldWithoutParam()); 11 Console.WriteLine("服務返回的結果是: {0}", proxy.GetHelloWorldWithParam("Learning Hard")); 12 } 13 14 Console.Read(); 15 } 16 17 } 18 }
此時的運行結果和前面客戶端返回的運行結果是一樣的。
五、總結
到這里,本文的內容就介紹結束了,本文主要解決了在WCF中如何實現操作重載的問題,實現思路可以概括為利用OperationContractAttribute類的Name屬性來實現操作重載,而客戶端的實現思路可以概括為重新代理類,利用信道Channel類帶對對應的服務方法進行調用,最后,實現了把WCF服務寄宿在Windows Services中,這樣WCF服務可以作為服務在機器上設置開機啟動或其他方式啟動了。在下一篇博文中將分享WCF服務契約的繼承實現。
本人所有源代碼下載:WCFServiceContract.zip