天天看點

WCF中的ServiceHost初始化兩種方式

在宿主程式中初始化ServiceHost有直接寫代碼和使用配置檔案兩種方式。使用ServiceHost首先要引用System.ServiceModel 命名空間。

1 代碼方式

using(ServiceHost host=new ServiceHost(typeof(HelloWordService)))
{
    host.AddServiceEndpoint(typeof(IHelloWordService),
        new BasicHttpBinding(), new Uri("http://localhost:10000/HelloWorldService"));
    host.AddServiceEndpoint(typeof(IHelloWordService),
        new NetTcpBinding(), new Uri("net.tcp://localhost:10001/HelloWorldService"));
    if (host.State != CommunicationState.Opening)
        host.Open();
}      

2 配置檔案方式

配置檔案代碼:

<services>
  <service behaviorConfiguration="serverBehavior" name="HelloWordService">
    <endpoint address="http://localhost:10000/HelloWorldService"
              binding="basicHttpBinding" contract="IHelloWordService"></endpoint>
    <endpoint address="net.tcp://localhost:10001/HelloWorldService"
              binding="netTcpBinding" contract="IHelloWorldService"></endpoint>
  </service>
</services>      

當然也可以使用基位址的方式來配置

<services>
  <service behaviorConfiguration="serverBehavior" name="HelloWordService">
    <endpoint address="HelloWorldService"
              binding="basicHttpBinding" contract="IHelloWordService"></endpoint>
    <endpoint address="HelloWorldService"
              binding="netTcpBinding" contract="IHelloWorldService"></endpoint>
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:10000/"/>
        <add baseAddress="net.tcp://localhost:10001/"/>
      </baseAddresses>
    </host>
  </service>
</services>      

配置好配置檔案後就宿主程式中就很簡單了,如下:

using(ServiceHost host=new ServiceHost(typeof(HelloWordService)))
{
    if (host.State != CommunicationState.Opening)
        host.Open();
}      

繼續閱讀