Search code examples
c#.netwcfwindows-services

WCF works as application, but not as service


I have a WCF server that I can run as a service or as a windows forms application. When I run it as a Windows Forms application I can connect to it via my client application. However when I run it as a service using the same code, I cannot connect to it. I have confirmed that the service is running and doing its work. Below is the server's config file.

<system.serviceModel>
  <services>
    <service name="Cns.TrafficCopService.ManagementService">
      <host>
        <baseAddresses>
          <add baseAddress="http://localhost:8000/TrafficCop/ManagementService" />
        </baseAddresses>
      </host>
      <endpoint address="" binding="wsHttpBinding" contract="Cns.TrafficCopService.IManagementService" />
    </service>
  </services>
</system.serviceModel>

and its hosting code, called 100 milliseconds after OnStart is called:

if (this.serviceHost != null)
{
    this.serviceHost.Close();
}

this.serviceHost = new ServiceHost(typeof(ManagementService));
this.serviceHost.Open();

and the client's config file:

<system.serviceModel>
  <bindings>
    <wsHttpBinding>
      <binding name="WSHttpBinding_IManagementService" />
    </wsHttpBinding>
  </bindings>
  <client>
    <endpoint
        address="http://localhost:8000/TrafficCop/ManagementService"
        binding="wsHttpBinding"
        bindingConfiguration="WSHttpBinding_IManagementService"
        contract="IManagementService"
        name="WSHttpBinding_IManagementService">
    </endpoint>
  </client>
</system.serviceModel>

Solution

  • Could you post the rest of your code for hosting the service?

    Your class that starts the service should be inheriting from "ServiceBase" and should implement the "OnStart" and "OnStop" methods. These methods are invoked by the service console to start and stop the service process, so your ServiceHost should be opened/closed in these methods. Just wondering if maybe you're not doing that.