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.RuntheProgramclass. TheHostFactory.Runmethod accepts anAction<HostConfiguration>as a parameter, which we can define by opening a lambda method. Inside of the lambda method, the variablexrepresents theHostConfigurationparameter and exposes all of it's methods. - The first configuration specified is
x.Service<TService>(Action<ServiceConfigurator>). Just like at theHostFactory.Runlevel, we open an additional lambda method with a variablesthat exposesServiceConfiguratormethods. Inside here, we tellTopshelfhow 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 ofExampleDerivedPeriodicServiceand passing aconst intparameter representing 20 seconds. We also pointWhenStartedandWhenStoppedto ourStartandStopmethods. 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.Runmethod and executed. The service will start running after executing the configuration.