Building Windows Services using Topshelf

Hello again 🙂 Visibly this is going to be my first technical post here. I hope you’ll find it useful.

Windows Services

Recently I came up with a need to create an application, which executes some tasks in the background based on file system’s events. “That’s easy”, one would say. “Build Windows Service app”, he would add. Sure, that was also my first idea.

I think that’s very common that we want to create an application without any GUI, which purpose is just to do something in the background. Moreover we’d like it to be independent from the user running it – we want it to be running all the time, without having to manually launch it – especially when the application is running on customer’s environment, where we can’t be logged in all the time running the application.

Here comes the service – long-running executable with no user interface, which runs in its own Windows session. Such application can be:

  • executed by any user created in the system (e.g. with specific security policies assigned),
  • started automatically when the system launches,
  • automatically restarted in case of errors,
  • at any time started, paused, stopped or restarted.

Even if you’ve never developed any service applications, you are using many of them – check your services.msc to see the list of services currently running in your system.

Topshelf

Visual Studio 2015 provides a template to create Windows Service application and probably I could finish my post here. However, I would like to share with you an even easier way of building services: to do it with Topshelf – a very lightweight open-source library, which purpose it to make services development, debugging and deployment painless. Topshelf allows the developer to focus on service’s functionality, instead of wasting time interacting with .NET Framework’s build-in services support. There is also no more need to install your service using InstallUtil or learn how to attach your Visual Studio debugger to running service to detect issues.

Using Topshelf it’s enough to create console application, add one service class with public Start and Stop methods, configure service’s startup parameters (its name, display name, description etc.) and you’re ready to go. Below we’ll see how to do it.

Creating Windows Service application

After creating console application in Visual Studio, add Topshelf to the project by installing it from Nuget:

Topshelf - Nuget

Adding service class

Then, create service class, which is responsible for executing your service’s logic:

class FileWatcherService { public bool Start() { // Initialize your service application here return true; } public bool Stop() { // Executed when the service is stopped // Dispose your objects here etc. return true; } } read more...