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
- Setting up the host using the
HostFactory.Run
theProgram
class. TheHostFactory.Run
method accepts anAction<HostConfiguration>
as a parameter, which we can define by opening a lambda method. Inside of the lambda method, the variablex
represents theHostConfiguration
parameter and exposes all of it's methods. - The first configuration specified is
x.Service<TService>(Action<ServiceConfigurator>)
. Just like at theHostFactory.Run
level, we open an additional lambda method with a variables
that exposesServiceConfigurator
methods. Inside here, we tellTopshelf
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 ofExampleDerivedPeriodicService
and passing aconst int
parameter representing 20 seconds. We also pointWhenStarted
andWhenStopped
to ourStart
andStop
methods. Note: XmlConfigurator.ConfigureAndWatch() is used to configure log4net on service start in our example. -
x.RunAsLocalSystem();
specifies the run as user privileges - The next three configuration lines are for specifying the Windows service description, display name, and service name.
- 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.