Search code examples
c#topshelf

Topshelf does not call service start


I am seeing different behaviour in Topshelf depending on whether I start the application in standalone mode or installed as a service. I have tried Topshelf 3.3.1 and 4.1.

I am using a service that implements ServiceControl, which works fine in standalone mode. When trying to start the installed service, I receive the message that the service took too long to respond to control requests.

var resultCode = HostFactory.Run(x =>
{
    x.Service<ServiceControl>(sc =>
    {
        sc.ConstructUsing(() =>
        {
            Console.WriteLine("GET INSTANCE!");
            return new WorkerService();
        });
        sc.WhenStarted((s, h) =>
        {
            Console.WriteLine("START!");
            return s.Start(h);
        });
        sc.WhenStopped((s, h) =>
        {
            Console.WriteLine("STOP!");
            return s.Stop(h);
        });
        sc.BeforeStartingService(() => Console.WriteLine("BEFORE START!"));
    });

    x.SetDescription("WorkerService");
    x.SetDisplayName("WorkerService");
    x.SetServiceName("WorkerService");
});

This is a very verbose version of calling a service (with lots of console output), but even the calls to ConstructUsing or BeforeStartingService do not produce any console output, while log calls inside the Service<> lambda produce output.

I am left quite clueless here, but also have not been able to reproduce this with a minimal sample. The timeout comes after about 3-4 seconds, without any visible attempt to start the service. Starting the service thread from the program main does work without exception.

Starting the service with WorkerService.exe works as expected, starting it with WorkerService.exe start (which starts the service) does not work.

As this happens with Topshelf 3 and 4, it most likely is something I am doing wrong inside the application. Any pointer into the right direction is very much appreciated.


Solution

  • I have a lead now: as part of loading the config we are loading a file from the roaming AppData and it looks like if the file is not accessible, an exception is thrown and silently discarded. If the file does not exist, the service starts as expected and everything works.

    So the basic problem is that an uncaught exception was thrown before the Topshelf service config part was started, which seems to be used to forward some output to the command line application when calling the exe with the start parameter.

    I will try to investigate on that as time allows and to contribute to Topshelf with the learnings.