Creating a Windows service with Topshelf

Update: This post still gets a fair amount of traffic, so I’d like to direct your attention towards my newer post on TopShelf 2.0: On The Bus With MassTransit #1
Update: Please go to the updated guide to Topshelf, which covers how to get started with Topshelf 3

Just wanted to share my experiences regard ing the super cool mini framework, Topshelf – a bi-product from the development of MassTransit. When Dru and the other guys were working on MassTransit, they needed to create Windows services a lot, which led to the separation of the Windows service stuff from the other stuff – and now they call it Topshelf.

You use Topshelf by creating a console application. In the Main method, you create a configuration, which you hand over to Topshelf. Then, everything just works as expected.

Topshelf requires that you to use an IoC container hidden behind the common service locator interface, which is neat because then it’s up to you to decide which container to use. In this example, I am using Windsor.

Creating a service is as simple as this:

Everything in the snippet above works as expected. Note how I create my Windsor container and store it behind WindsorServiceLocator, which is my trivial implementation of the IServiceLocator interface. This way, Topshelf will pull the specified service type(s) ( SomeService in the sample) from the container, and call the specified methods to start/stop (and possibly pause/resume) the service.

Note also how I specify that my service has a dependency on message queueing – neat!

Running and debugging the service is as easy as executing the .exe.

Installing/uninstalling can be done with

Nifty!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.