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.

Bring back the types!

When you’re working with C# and reflection, you might end up in a situation where you have “lost” the type. For example, if you’ve deserialized an incoming message of some kind, you might have code that needs to do this:

Usually, when you want to do different stuff depending on the type of an object, you just call that object and let it do what it deems reasonable. That’s a good object-oriented way of delegating behavior to objects, totally anti-if campaign compliant and all. But in cases where the object you need to act upon is an incoming DTO, it’s usually not a good approach to put logic on that DTO.

This is a good time to do a “handler lookup” [1. I don’t know if there’s a better name for this pattern. I tried to ask Twitter, but I mostly got “it’s usually not a good idea to do that” – well, most patterns are usually not a good idea: all patterns should be applied only in cases where they make sense </stating-the-obvious>] in your IoC container for something that can handle an object of the given type. It goes like this: Given message: T, find handler: IHandle<T> and invoke handler with message.

In C#, that might look like this:

That’s not too bad I guess, but working at this untyped level for longer than this turns out to be cumbersome and hard to read and understand. It wouldn’t take more than a few lines more of invoking things via reflection before the dispatch of the message has turned into a mess! And then add the fact that exceptions thrown in method invocations made with reflection will be wrapped in TargetInvocationExceptions.

Consider this alternative approach where I use reflection to invoke a private generic method, closing it with the type of the message:

This way, the Dispatch method can have the bulk of the logic and it does not need to bother with the reflection API. Nifty!

Domain events salvation example

One of the immensely awesome things that Udi Dahan has – if not invented, then at least brought to my attention – is the awesome “domain events – salvation” pattern.

If you’re familiar with the onion architecture, you’ve probably more than once experienced the feeling that you had the need to pull something from your IoC container some place deep in your domain model. In my experience, that often happens when you have a requirement on the form “when something happens bla bla, then some other thing must happen bla bla” where “something” and “some other thing” aren’t otherwise related.

An example could be when a new account (a.k.a. a customer that we mean to do business with) is registered in the system, we should make sure that our credit assessment of the account is fresh enough that we dare do the businesss.

I’ve found that the “domain events – salvation” provides a solution to that problem. Check this out:

“Whoa, what was that?” you might ask… that was a domain object that did some stuff, and in the end it raised a “domain event”, telling to the world what just happened. And yes, that was a domain object calling out to some static nastiness – but I promise you, it isn’t as nasty as you may think.

I’d like to assure you that the Account class is fully unit testable – i.e. it can be tested in isolation, just like we want. And that’s because we can abstract the actual handling of the domain events out behind an interface, IHandleDomainEvents, which is what actually gets to take care of the domain events – something like this:

and then IHandleDomainEvents can be implemented in several flavors and “injected” into the domain as a static dependency, e.g. this bad boy for testing:

which can be used by installing a new instance of it in the setup phase of each test, and then running assertions against the collected domain events in the assert phase.

The coolest part though, is the production implementation of IHandleDomainEvents – it may look like this:

thus delegating the handling of domain events to all implementors of ISubscribeTo<TDomainEvent>. This way, if I have registered this guy in my container:

I can kick off a new credit assessment workflow when a new account is registered, and everything is wired together in a way that is semantically true to the domain. Also, my domain object suddenly get to pull stuff from the container (albeit in an indirect fashion), without even knowing about it!

Developing .NET applications very rapidly

In my current position as an agile .NET dude at d60, I have already found myself in need of rapidly building several small applications and services from scratch.

This way of working reminds me a lot about some of the things that Dan North talked about in his “From months to minutes – upping the stakes” talk at GOTO Aarhus 2010.

In the talk, Dan described how he was part of a team that would rapidly prototype and deliver working systems to some stock exchange or something, and in doing this they would often start from scratch and replace the existing applications, instead of adapting old ones. The advantage is that you get to take some shortcuts when you’re making fairly short-lived applications, you don’t have to carry the burden of old legacy crap, you get to re-do, possibly undo(?) almost every decision some time, and you become really good at building stuff from scratch!

So, this is cool, and I think he said a lot of things that really make sense. But how can you build stuff very rapidly when you’re a .NET developer in a Microsoft shop, and your customer has based everything on Microsoft technology? You would think that a .NET developer would be slow compared to the hip coders working with Node.js, Clojure and [insert hip new technology here]…?

Well, it just so happens that .NET developers are actually pretty lucky in that regard. In this post, I’d just like to go through a few of the things that enable us to deliver stuff really quickly, both .NET and not-necessarily-.NET-things.

Git and GitHub

Like all sensible coding teams, we have moved to distributed source control. We have some pretty skilled Git-people among our developers, so Git was the natural choice. And since we’re not really interested in maintaining our own servers, it makes the most sense to have some hosted Git repositories somewhere – and for that, we got a company account at GitHub, because it’s a great place to host Git repositories.

Git’s branching model is just so extremely fast and lightweight that I’m wondering how I ever managed to get anything done in Subversion. Well, I guess I just didn’t update & commit that often then.

Is anyone still using Subversion? Why?


We have our own locally hosted TeamCity server to check out our code from GitHub, build it, run tests, create NuGet packages etc. Configuring and maintaining TeamCity is really easy compared to CruiseControl.NET, which I used to use – and with the extremely cool feature branch support of TeamCity 7.1, our build server will automatically check out, build, and test my branch if I name it feature-whatever_I_am_working_on when I push it to GitHub!


When you want to build stuff rapidly in .NET, there’s really no way you can ignore NuGet – this is how we get to quickly pull down all of the open source libraries and frameworks that we’re using to build cool stuff.

In addition to the free open source stuff, we also NuGet-pack all of our purchased libraries if they’re not already in a .nupkg. And finally, we pack our own shared libraries as NuGet packages as well (actually, TeamCity does this for us automatically on every successful build…), which is how we distribute shared assemblies like e.g. assemblies with Rebus messages.

NuGet has been really easy and smooth in this regard. I’m sorry that I never tried OpenWrap, though – I’m wondering if anyone is using that, or if everybody has moved to NuGet?

Our own NuGet package repository

In order to reduce the friction with NuGet, we have our own NuGet package repository. is just damn slow, and it doesn’t host all of our 3rd party and home-rolled packages.

At first, we used TeamCity to do this, but the NuGet extension in Visual Studio doesn’t remember your credentials, so you have to constantly punch in your username and password if you’ve enabled authentication. This was just too tedious.

Then we hosted our own stand-alone NuGet Server, which would have been OK if it weren’t for the fact that we’re often working outside of our office, and often on other companies’ VPNs. This doesn’t go well with a privately hosted NuGet server.

But then someone had the crazy idea that we should use DropBox as our NuGet repository! This is as crazy as it is ingenious, because we’re already using DropBox to share documents and stuff, so it didn’t really require anything to just throw all of our NuGet packages into a shared folder… which is what TeamCity also does whenever it has packed up something for us, immediately synchronizing the new package to everyone who’s connected to a network.

This way, we can always get to include our NuGet packages, even when we’re building new stuff on a train with a flaky internet connection. As I said: Crazy, yet ingenious!

Free choice of frameworks and tools

Last, but not least, I think a key to rapidly building stuff is to free developers’ hands so that they can use the tools they like to use best and feel are best for the given task.

It seems many companies are afraid that developers might pollute their applications with questionable libraries and bad decisions, but my feeling is that most developers are totally capable of handling this freedom and will respond with a sense of responsibility and care.


These were a couple of things that I could think of that help us build cool stuff and deliver often. As I may have already insinuated, I’m not sure this way of working would work on large monolithic applications that must live for very long.

But then again, in my experience many systems live for too long because they’ve become too huge, and thus too big and expensive to replace – it is often very healthy for systems to be divided into smaller applications that are well integrated, but each application in itself is fairly small and decoupled and thus doesn’t constitute a huge risk and equally huge endavour to replace.

Locking oneself out of SQL Server and the good old registry diff trick

Probably one of the oldest tricks in the book, but definitely one that should not be forgotten, is the Good Old Registry Diff Trick. You see, the other day I accidentally locked myself out of my local SQL Server by making a classic mistake: I deleted my own login!

Well, actually I had created a SQL login that I planned on using after having deleted the login used by my Windows account, but I had forgotten til enable the “Mixed mode authentication” setting, and thus only Windows authentication was allowed.

A little bit of Googling revealed a blog post that mentioned a “LoginMode” key somewhere in the machine’s registry, but my registry did not contain the branch mentioned in the blog post.

Good Old Registry Diff Trick to the rescue!

I went into another machine with a functional SQL Server that I could access, and made sure that only Windows authentication was allowed. Then I used Regedit to export the entire contents of the HKEY_LOCAL_MACHINE hive into a file called “before.reg”. Then I went in and changed authentication mode to “Mixed mode”, and repeated the export into another file, “after.reg”.

Then I loaded a diff tool with the following two files, giving me this:

which revealed that the [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQLServer] branch had the “LoginMode” key, which I could then change from “1” to “2” in order to allow “Mixed mode authentication” on my almost-impenetrable SQL Server, allowing me to log in.

Thank you, Good Old Registry Diff Trick.

Little nifties #1

Almost always, the first extensions methods I add to a system are these:

which allows me to format any sequence of stuff sensibly, easily, and inline, e.g. like so:

and so:

and so:


Assuring that those IWantToRunAtStartup can actually run at startup

When building NServiceBus services based on the generic host, you may need to do some stuff whenever your service starts up and shuts down. The way to do that is to create classes that implement IWantToRunAtStartup, which will be picked up by the host and registered in the container as an implementation of that interface.

When the time comes to run whoever wants to run at startup, the host does a

to get all the relevant instances (or something similar if you aren’t using Windsor…).

If, however, one or more instances cannot be instantiated due to missing dependencies, you will get no kind of warning or error whatsoever! [1. At least this is the case when using Castle Windsor – I don’t know if this is also the behavior of other IoC containers… Maybe someone can clarify this…?] This means that the service will silently ignore the fact that one or more IWantToRunAtStartups could not be instantiated and run.

In order to avoid this error, I have written a test that looks somewhat like this:

I admit that the code is kind of clunky even though I distilled the interesting parts from some of the plumbing in our real test… moreover, our real test is iterating through all the possible configurations our container can have – one for each environment – so you can probably imagine that it’s not pretty 🙂

But who cares??? The test has proven almost infinitely useful already! Whenever something that wants to run at startup cannot run at startup, TeamCity gives us error messages like this:

Shouldly – better assertions

Today I came across Shouldly, as I followed a link in a tweet by Rob Conery. I have a thing for nifty mini-projects, so I immediately git clone‘d it, and pulled it into a small thing I am building.

What is Shouldly? Basically, it’s just a niftier way of writing assert statements in tests. It fits right in between NUnit and Rhino Mocks, so you will get the most out of it if you are using those two for your unit tests. Check out this repository test – first, arrange and act:

and then, usually the assert would look something like this:

– yielding error messages like this:

which is probably OK and acceptable, because how would NUnit know any better than that?

Check out what Shouldly can do:

– yielding error messages like this:

which IMO is just too nifty to ignore!

Shouldly takes advantage of the fact the the current StackTrace has all the information we’re after when the assert is an extension method, which is extremely cool and well thought out.

Moreover, it integrates with Rhino Mocks, yielding better messages when doing AssertWasCalled stuff: Instead of just telling that the test did not pass, it tells you exactly which calls were recorded and which one was expected – a thing that Rhino Mocks has always been missing.

Conclusion: YourNextProject.ShouldContain("Shouldly")

Castle Windsor debugger visualization

A while ago, I noticed that Krzysztof Ko?mic was tweeting regularly about adding debugger visualization to Windsor. At the time, I wasn’t really paying attention, so I didn’ t actually understand what he was doing.

Today, I was coding some stuff, and I downloaded the latest and greatest Windsor 2.5 (from August 2010), and after a while I found myself stepping through some code in a small web application I was building from scratch – and that’s when I found out what he was rambling about…. check this out:

Windsor debugger visualization

See how the container renders itself as a list of all the components it contains, followed by a list of “Potentially Misconfigured Components”…?

How cool is that? (pretty cool, that’s how cool it is!)

Not a ground-breaking earth-shaking feature on the grand scale of cool stuff, but sometimes it’s the little things…

(I’m puzzled, however, as to why the headline says “Count = 4” in the “Potentially Misconfigured Components” section when the count is clearly 2…?)