Configuring a Topshelf Service in a Console Application - LessonsLearnedInDotNET/LL.NET.Topshelf GitHub Wiki

Topshelf allows console applications to be installed as a Windows service. This is an awesome tool because it allows you to debug an application as if it were a console, which is how a lot us learned how to program so it's instinctual. The configuration looks like the following:

        HostFactory.Run(x =>
        {
            x.Service<ExampleDerivedPeriodicService>(s =>
            {
                s.ConstructUsing(name => new ExampleDerivedPeriodicService(TWENTY_SECONDS));
                s.WhenStarted(tc =>
                {
                    XmlConfigurator.ConfigureAndWatch(new FileInfo(".\\log4net.config"));
                    tc.Start();
                });
                s.WhenStopped(tc => tc.Stop());
            });

            x.RunAsLocalSystem();

            x.SetDescription("Example Derived Periodic Service");
            x.SetDisplayName("ExampleDerivedPeriodicService");
            x.SetServiceName("ExampleDerivedPeriodicService");
        });

Note: The following description is a slight adaptation of the introduction in the Topshelf documentation

  1. Setting up the host using the HostFactory.Run the Program class. The HostFactory.Run method accepts an Action<HostConfiguration> as a parameter, which we can define by opening a lambda method. Inside of the lambda method, the variable x represents the HostConfiguration parameter and exposes all of it's methods.
  2. The first configuration specified is x.Service<TService>(Action<ServiceConfigurator>). Just like at the HostFactory.Run level, we open an additional lambda method with a variable s that exposes ServiceConfigurator methods. Inside here, we tell Topshelf how to create the service, what to do when the service starts, and what to do when the service stops. In our example, Topshelf is configured to create an instance of ExampleDerivedPeriodicService and passing a const int parameter representing 20 seconds. We also point WhenStarted and WhenStopped to our Start and Stop methods. Note: XmlConfigurator.ConfigureAndWatch() is used to configure log4net on service start in our example.
  3. x.RunAsLocalSystem(); specifies the run as user privileges
  4. The next three configuration lines are for specifying the Windows service description, display name, and service name.
  5. At the close of the lamba, the configuration is returned to the HostFactory.Run method and executed. The service will start running after executing the configuration.
⚠️ **GitHub.com Fallback** ⚠️