淺析概括WCF自托管宿主
學(xué)習(xí)WCF時(shí),你可能會(huì)遇到WCF自托管宿主問題,這里將介紹WCF自托管宿主問題的解決方法,在這里拿出來和大家分享一下。利用WCF提供的ServiceHost<T>提供的Open()和Close()方法,可以便于開發(fā)者在控制臺(tái)應(yīng)用程序,Windows應(yīng)用程序乃至于ASP.NET應(yīng)用程序中托管服務(wù)。不管自宿主的環(huán)境是何種應(yīng)用程序,實(shí)質(zhì)上托管服務(wù)的方式都是一致的。例如在控制臺(tái)應(yīng)用程序中:
- using (ServiceHost host = new ServiceHost(typeof(DocumentsExplorerService)))
- {
- host.Open();
- Console.WriteLine("The Service had been launched.");
- Console.Read();
- }
#T#ServiceHost實(shí)例是被創(chuàng)建在應(yīng)用程序域中,因此我們必須保證宿主進(jìn)程在調(diào)用服務(wù)期間不會(huì)被關(guān)閉,因此我們利用Console.Read() 來阻塞進(jìn)程,以使得控制臺(tái)應(yīng)用程序能夠一直運(yùn)行,直到認(rèn)為地關(guān)閉應(yīng)用程序。如果是Windows應(yīng)用程序,則可以將創(chuàng)建ServiceHost實(shí)例的代碼放在主窗體的相關(guān)代碼中,保證服務(wù)WCF自托管宿主不會(huì)被關(guān)閉。相應(yīng)地,我們需要配置應(yīng)用程序的app.config配置文件:
- <configuration>
- <system.serviceModel>
- <services>
- <service name="BruceZhang.WCF.DocumentsExplorerServiceImplementation.DocumentsExplorerService" behaviorConfiguration="DocumentExplorerServiceBehavior">
- <host>
- <baseAddresses>
- <add baseAddress="http://localhost:8008/DocumentExplorerService"/>
- </baseAddresses>
- </host>
- <endpoint
- address=""
- binding="basicHttpBinding"
- bindingConfiguration="DocumentExplorerServiceBinding"
- contract="BruceZhang.WCF.DocumentsExplorerServiceContract.IDocumentsExplorerService"/>
- <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
- </service>
- </services>
- <bindings>
- <basicHttpBinding>
- <binding name="DocumentExplorerServiceBinding" sendTimeout="00:10:00" transferMode="Streamed"
- messageEncoding="Text" textEncoding="utf-8" maxReceivedMessageSize="9223372036854775807">
- </binding>
- </basicHttpBinding>
- </bindings>
- <behaviors>
- <serviceBehaviors>
- <behavior name="DocumentExplorerServiceBehavior">
- <serviceMetadata httpGetEnabled="true"/>
- </behavior>
- </serviceBehaviors>
- </behaviors>
- </system.serviceModel>
- </configuration>
注意,配置文件中的服務(wù)名必須包含服務(wù)契約以及服務(wù)類的命名空間。此外,在配置文件中我通過<baseAddresses>標(biāo)簽為服務(wù)添加了基地址,因此在endpoint中,address為""。


















