淺析概括WCF自托管宿主
學習WCF時,你可能會遇到WCF自托管宿主問題,這里將介紹WCF自托管宿主問題的解決方法,在這里拿出來和大家分享一下。利用WCF提供的ServiceHost<T>提供的Open()和Close()方法,可以便于開發者在控制臺應用程序,Windows應用程序乃至于ASP.NET應用程序中托管服務。不管自宿主的環境是何種應用程序,實質上托管服務的方式都是一致的。例如在控制臺應用程序中:
- using (ServiceHost host = new ServiceHost(typeof(DocumentsExplorerService)))
- {
- host.Open();
- Console.WriteLine("The Service had been launched.");
- Console.Read();
- }
#T#ServiceHost實例是被創建在應用程序域中,因此我們必須保證宿主進程在調用服務期間不會被關閉,因此我們利用Console.Read() 來阻塞進程,以使得控制臺應用程序能夠一直運行,直到認為地關閉應用程序。如果是Windows應用程序,則可以將創建ServiceHost實例的代碼放在主窗體的相關代碼中,保證服務WCF自托管宿主不會被關閉。相應地,我們需要配置應用程序的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>
注意,配置文件中的服務名必須包含服務契約以及服務類的命名空間。此外,在配置文件中我通過<baseAddresses>標簽為服務添加了基地址,因此在endpoint中,address為""。