wcf自托管多项服务

时间:2013-12-23 19:32:49

标签: c# visual-studio-2010 wcf hosting self-hosting

在我的项目中,我有两个服务Service1和Service2(即服务合同)。我希望这两个服务器是使用console自托管的。为此我使用名为“myservice”的服务并实现两个接口,即IService1和IService2之类的< / p>

public class myservice : IService1,IService2
...
....


ServiceHost serviceHost = new ServiceHost(typeof(myservice));
serviceHost.Open();

使用的端点:

 <service behaviorConfiguration="myBehavior" name="myservice">
    <endpoint address="sa1" binding="netTcpBinding" contract="IService1"/>
    <endpoint address="sa2" binding="netTcpBinding" contract="IService2"/>
  <host>
    <baseAddresses>
      <add baseAddress="net.tcp://localhost:8001/" />
    </baseAddresses>
  </host>
</service>

我希望这两个是单独的服务,即服务名为Service1和Service2(而不是myservice),具有tcp绑定和自托管。任何代码/帮助/建议都赞赏。

1 个答案:

答案 0 :(得分:3)

如果必须具有两个单独的服务 - 那么您需要两个单独的服务实现类以及两个单独的ServiceHost实例:

public class Service1 : IService1
{
  ...
}

public class Service2 : IService2
{
  ...
}


ServiceHost serviceHost1 = new ServiceHost(typeof(Service1));
serviceHost1.Open();

ServiceHost serviceHost2 = new ServiceHost(typeof(Service2));
serviceHost2.Open();

端点配置:

<service name="YourNamespace.Service1" behaviorConfiguration="myBehavior" >
    <endpoint address="sa1" binding="netTcpBinding" contract="IService1" />
    <host>
       <baseAddresses>
         <add baseAddress="net.tcp://localhost:8001/" />
       </baseAddresses>
    </host>
</service>
<service name="YourNamespace.Service2" behaviorConfiguration="myBehavior" >
    <endpoint address="sa2" binding="netTcpBinding" contract="IService2" />
    <host>
       <baseAddresses>
         <add baseAddress="net.tcp://localhost:8002/" />
       </baseAddresses>
    </host>
</service>