Back2Basics - Windows Services in Powershell & TopShelf

When designing systems, distributed or otherwise, engineers create applications which can be roughly classified into two major categories:

(a) Long running, background processes which require multiple steps / dependencies / workflow items to complete and

(b) (mostly) interactive shorter duration programs. In Microsoft application landscape, the earlier category of daemon / majordomo style apps are best served by building Windows Services.

Windows services, regardless of what someone tells you, are not dead, archaic or going out of commission anytime soon. Windows services are essentially the defacto bread and butter of all head-less/without UI, long running background processes; for instance you can see that your RabbitMQ server runs as a windows service, so is your favorite anti-virus, and the vpn client to name a few. Having said that, despite Microsoft's best efforts and their amazing IDE, debugging and testing a windows service has always been difficult to say the least. Personally I have always written a helper utility console wrapper around the service library (along with unit tests project) to check the functionality of the underlying service's start() routine. This is not ideal, or completely fool proof because service start and execution under the specified user is not well tested this way. But this at least gives you a fundamental bare minimum way of testing out the functionality before you proceed with running the app, as a service.

TopShelf

Now to the good news, if you have not heard yet, there is TopShelf! to the rescue. Few years ago Topshelf, an easy service hosting framework for building Windows services using .NET, was released as a github project. It is easy to integrate, works like a charm (read nuget pakcage!), and makes it super easy to build and test modern day windows services, in a easy to debug interactive execution manner. Here is intro info from their website.

Topshelf is a framework for hosting services written using the .NET framework. The creation of services is simplified, allowing developers to create a simple console application that can be installed as a service using Topshelf. The reason for this is simple: It is far easier to debug a console application than a service. And once the application is tested and ready for production, Topshelf makes it easy to install the application as a service.

Here is how to get started. Go forth and explore.

Powershell

Why on earth someone would want to write a windows service using powershell? Well for prototyping a service proof of concept, a service script written in windows powershell might be an excellent choice. Jean-Francois Larvoire wrote an interesting article "Windows PowerShell - Writing Windows Services in PowerShell" in May'sMSDN Magazine which explains how you can write and test such scripts easily. More power to devOps.

Happy Coding!

Share