Topshelf and IoC containers

To top off my previous post with an example on how almost any kind of application can be hosted as a Windows Service, I’ll show an example on how Topshelf can be used to host an IoC container.

As most developers probably know, an IoC container functions as a logical application container of sorts, helping with creating stuff when stuff needs to be created, and disposing stuff when stuff needs to be disposed, keeping whatever needs to be kept alive alive for the entire duration of the application lifetime.

This way, when we have this Topshelf-IoC-container framework in place, we can use it to activate all kinds of applications.

I’ll show how it’s done with Castle Windsor, but I think it should be fairly easy to port this solution to any other IoC container.

Create a service class that holds the container

First, let’s create a class that implements the Start/ Stop methods of ServiceControl – this class will initialize its Windsor container when it starts, and dispose it when it stops.

I’ve added some logging for good measure – when you’re a backend kind of guy, you come to appreciate a systematic and consistent approach towards logging in your Windows services, and I’m no exception.

Use Topshelf to activate the service class

Now we can have our RobotService activated as a Windows Service by adding the following C# spells:

Please note that Topshelf needs a little extra help with logging unhandled app domain exceptions, so I’ve added a little bit of Log.Fatal at the top.

Add components to the container to actually do something

Now, just to show some real action, I’ve added a single Windsor installer that looks like this:

As you can see, it will start a System.Timers.Timer, configured to periodically log a cheerful statement to the log and shove it in the container to be disposed when the application shuts down. It shouldn’t take too much imagination to come up with more useful and realistic tasks for the timer to perform.

This is actually all there is to it! Of course it can be customized if you want, but what I’ve shown is the only stuff that is necessary to create a full-blown Windows Service that manages the lifetime of application components and logs its work in a way that makes the service monitorable, e.g. by Microsoft SCOM and/or Splunk or whichever way you like to throw your logs.

As a public service, I’ve put this small example project in a GitHub repository for your cloning pleasure. Also, if you have any comments, please don’t hesitate to send them my way. Pull requests are also accepted 🙂

Updated guide to Topshelf

topshelfI have written about Topshelf several times before, but the API has gone through a few changes over the last couple of years – and since my Topshelf posts are, for some reason, constantly (according to my stats) being (re)visited, I thought it would be in order to show the most current version of Topshelf in action…

Oh, and if you’re reading this and you don’t know what Topshelf is – it’s a library that helps you to quickly make your C# console application into a Windows Service that can easily be F5-debugged as well as installed as a proper Windows Service.

This is how you do it:

Create a new console application

Just do it. Name it something cool, like RobotsOnFire.

Pull in Topshelf with NuGet

Either reach out for your mouse and clickety click a few dozen times… me? I prefer to go

in the Package Manager Console, and this is how I avoid getting a tennis elbow even before I’ve written one line of code.

Remove unnecessary using directives and other redundant crap

This looks stupid – it makes you look like a person who doesn’t care:

This looks good – it reaks of the finicky meticulousness that is you:

Now, modify your Program class

into something like this:

and then press F5, and then you’ll be looking at something like this:


Wow! That was easy, right?! In order to actually do something in your Windows Service, you start a thread or a timer or something similar in the Start method and make sure that what you started is stopped again in the Stop method. In other words, the Start and Stop methods must not block – otherwise, Windows Service Control will not start the service properly.

Since this bad boy is an ordinary Console Application on the surface, it can be F5-debugged and run by executing RobotsOnFire.exe. But in addition to that, you can do this (in an elevated command prompt):


which results in Robots On Fire turning up as a Windows Service in Windows:


Now, let’s uninstall it again:


and then let’s customize a couple of settings:

which, after installing it again, will show up like this:


Topshelf has many additional things that can be customized – e.g. you can perform actions in connection with installing/uninstalling the service, make it install to be run under various system accounts, and – this is one of the cooler things – you can declare a dependency on e.g. a local SQL Server, a local IIS, or any other locally running Windows Service – this way, services will always be started/stopped in the right order, ensuring that e.g. your MSMQ-dependent service is not started before the Message Queueing service.

On the bus with MassTransit #1

Update: If you want to read about Topshelf, please go to the updated guide to Topshelf, which covers how to get started with Topshelf 3

This is the first post in a series of posts on the open source service bus implementation, MassTransit. In order to push myself through learning it, I will do these posts as I go and document stuff I learn on the way.

This first post will be about one thing, that you’ll probably end up doing quite a few times while building your awesome messaging-based distributed system: Creating a service.

Check out TopShelf and build it

I’ve described how to use TopShelf before, but a lot has changed since then. TopShelf, at the time of writing, is now in version, and since 2.0 it has a feature called “shelving”, which is the ability to host any number of services beneath one Windows Service – just like IIS hosts web apps. This is pretty awesome, but today I’ll just show “the old API”, which IMO is still pretty slick!

First, make sure you have a working Ruby installation with Albacore ( gem install albacore). You’ll need these to build Topshelf.

Next, git clone git:// and build.bat. That should leave a bunch of binaries in the NET35 and NET40 folders beneath build_output. This is open source, baby!

Put your app on the TopShelf

Create a new “Console Application” and make sure to target the full .NET 4 framework (and not that bastard .NET 4 Client Profile thingie, which is default…)

Now add a reference to Topshelf.dll and log4net.dll. Punch in something like this:

This is all the necessary stuff to create a fully functional program, that can be run and debugged by running the resulting .exe – either from the command line, or with F5 inside Visual Studio.

Moreover, it can be installed as a Windows Service by going to the command line (as an administrator!) and executing NameOfYourApp.exe install. On my machine, I got this output:

Now I can net start MyBackend-service-name and net stop MyBackend-service-name on the command line, or I can go to Windows’ service control snap-in and pull the usual levers to control it. Nifty!

Now I have a perfectly functioning Windows Service that does nothing at all! Let’s output some stuff to see where we’ll put our code in a short while. Try extending the x => { ... } lambda to make the program look like this:

and a class that looks something like this:

Now, when I press F5, wait a little, and press Ctrl + C, I get this output on the console:

Awesome, huh?

I really like how TopShelf now uses a Func<TService> to construct its service instance via ConstructUsing, instead of depending on the common service locator as the old TopShelf did. This way, I can pull the instance from an IoC container if I want.

In the next post I will take a look at how to send a message from a web application when someone tries to register as a user.

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