Create Windows Service with Topshelf — Part 1
This blog post is part of the series How to: Create Windows Service that schedules jobs, logs and is configurable by means of dependency injection.
Topshelf is a Windows service framework for the .NET platform. It makes it easy to create a Windows service, test it, debug it, and ultimately install it into the Windows Service Control Manager (SCM). Developers don’t need to understand the complex details of service classes, perform installation via InstallUtil, or learn how to attach the debugger to services for troubleshooting issues. When developing with Topshelf, creating a Windows service is as easy as creating a console application. Once the console application is created, the developer creates a single service class that has public Start and Stop methods. With a few lines of configuration using Topshelf’s configuration API, the developer has a complete Windows service that can be debugged using the debugger and installed using the Topshelf command-line support.
Topshelf is an open-source project which is publicly available as a NuGet package. To read more about Topshelf, visit http://docs.topshelf-project.com/en/latest/overview/index.html.
To create Windows Service with Topshelf, you only need to create a console application after which you install it with a simple command line.
To get started, create a console application and install Topshelf via NuGet Package Manager.
Now, let’s define our service and what it should do when it gets started or stopped.
After that, we need to host it using Topshelf.
HostFactory.Run() configures and runs a service host, handling any exceptions and writing them to the log. As an argument it receives a configuration callback
Action<HostConfigurator> which in turn receives
HostConfigurator with which we can configure service’s name, display name, description.
We can also specify service’s security context, which defines its logon type. In sample code we use
hostConfigurator.RunAsLocalSystem() with which we specify that we want to run our service using Local System account, but you can specify other accounts as well — Local Service account, Network Service account, User account etc.
Finally, we need to tell
HostConfigurator how to create our service class object instance and provide hooks which will be called when service is started or stopped.
If we were to run our console application now, this would be the output.
To install our console application as a Windows Service, navigate to
bin/debug folder, and run
To uninstall, run
In next post, we will configure logging use log4net.