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!

Helping future me

Usually, when writing code, you adhere to some conventions on how your stuff should work. At least I hope you do – otherwise your code is probably a mess!

Sometimes, these conventions can be enforced by using some patterns to allow for compile-time checking – one example, that I can think of right now, is using the visitor pattern to implement multiple dispatch, which is explored a little bit in another post.

But what about conventions, that can only be checked at runtime? Well, how do we usually check stuff that can only be checked at runtime? – by writing tests, of course!

One project I am currently involved in, is written in ASP.NET MVC. All form posts are done using the automatic binding features of the framework, and I am following the convention that the names of my view models should end in “Form” – so as to enabling me to easily distinguish my form posting DTOs from my other view models. What is more natural, then, than performing the following test:

That is, I am running through all controller types, getting all actions, and checking the the parameter types are either in the array of accepted types ( IsPrimitiveType) or a “true poco” (which in this application is a simple view model whose name ends with “Form” and comes from the right assembly).

This way, I will always know which types are used to deserialize forms. Great! But what about that pesky MissingMethodException whenever I forget to provide a public default contructor in my form models? Easy as cake! That part is checked by the following test:

These two tests combined, will assert that nothing will go wrong when submitting forms in my ASP.NET MVC project. That’s just nifty! And I really like the notion that I am helping future me.

Playing around with the visitor pattern

I have been thinking a little bit about the visitor pattern recently. One of my most recent applications was in combination with a class, which would be used in a message distribution scenario.

The class’ reposibility is – given a list of email addresses – to look up any existing users in my application, and allow the caller to perform an action depending on whether the email belongs to a registered user or not. Pretty simple if you feel like juggling dictionaries and stuff, but I made an even simpler solution.

My email lookup service has the following interface:

And then I have two classes: EmailRecipient and UserRecipient which are both specializations of the abstract superclass Recipient – each containing either an email (a string) or an IUser depending on whether the service was able to look up a user.

Then I have another service, which functions as a message distributor. Given a list of email addresses, either an email or an internal message will be delivered to each recipient. This is a perfect application for the visitor pattern, because it allows us to avoid this kind of brittle code:

I have seen this kind of code in far too many places where inheritance is used. It is obviously very brittle, because what happens if someone adds another kind of Recipient? Nothing at first, because the code will compile like everything is allright. Only after the code is run, and we actually get in a situation where another kind of Recipient is encountered, do we get an error… and in the example above, I was courteous and threw an exception – but what if the original author had not done that? The program could have been silently failing for months before someone found out… yikes!

Another solution is to move the behavior into the specializations – e.g. into an implementation of an abstract SendMessage method on Recipient. But then the specializations would require a reference to either the emailService or the messageService, which would kind of turn the layering upside down, since the domain classes would need to know about some higher level services.

What we really want, is for a service to be able to behave differently depending on which specialization is encountered, and for that service to contain the logic to handle each specialization. And we want errors at compile-time if a specialization is not handled. Enter the visitor pattern…

One way to accomplish this is by using the visitor pattern as described by GoF. It’s pretty simple: Make a call to an abstract method which gets implemented by each specialization, and let that specialization make a suitable callback to identify itself. My visitor interface looks like this:

– and then each specialization must implement the abstract Visit method from the Recipient class:

and then invoke their correponding callback method passing themselves back.

Then my client can create an implementation of IRecipientVisitor, supplying it with the necessary services, allowing the visitor to do different stuff depending on the specializations. But that requires me to implement a class like this every time I have a reason to do different stuff:

Having done this a few times, implementing a new class each time which would be used only once, I started thinking about how to accomplish this with fewer lines of code. One thing that really bugged me, was that I needed to supply the visitor with all kinds of context data to allow the visitor to perform whichever action it would decide to carry out, depending on which Visit(...) method would be called. Then I came up with the generic visitor:

Now my message dispatch can be implemented like this:

Why is this great?

1. I get to implement multiple dispatch with all the safety of the visitor pattern. If I add a new specialization of Recipient, e.g. ErronousEmailRecipient, I add a new method to the IRecipientVisitor interface. That causes the RecipientVisitor to break, so I implement the new method in there as well, in turn causing the code to break everywhere the visitor is used (“break” in a good not introducing bugs-kind-of-way). That way I can be sure that I will know where to handle this new specialization.

2. I get access to the context I am already in. Instead of creating a new visitor and supplying it with sufficient context to carry out whichever actions it needs to perform, I can specify in a short and concise way what I want to do for each specialization, accessing any local variables inside of the scope my labdas are in. That’s just elegant and easy.

3. The code is where it is used. The distance from usage to implementation is zero. Of course, if the implementation is more complex, it may look more like so:

– which is still pretty terse and to-the-point compared to creating an entirely new dedicated class for this.

Way more nifty: Using compression at field level when persisting #2

In a previous post (here) I showed how the contents of a string property could be internally stored as a GZipped byte array for persistence. The code demonstrated how to achieve this, but not in a particularly pretty manner, because I did some nasty hacks inside the property’s setter and getter – i.e. I crammed all the zipping/unzipping stuff directly inside my domain class.

When using NHibernate for persistence you have another option, which I have recently learned about. So let’s rewrite the example from my previous post.
Read more

Tailoring a custom matcher for NMock

You’ll often hear proponents of test-driven development claim that unit testing is hard and that it forces them to open up their classes’ hidden logic for them to be testable. That might be true to some degree, but more often in my opinion you’ll find that designing your system to be testable also has the nifty side-effect of separating your logic into .. umm logical chunks… and what I really mean here is that your chunks have a tendency to become orthogonal, which is by far one of the best quality attributes of a system.

BUT that was not what I was going to say, actually – I just wanted to comment on a nifty thing, I recently found out: implementing my own Matcher to use with NMock.

An NMock Matcher is an abstract class, which requires you to implement the following members:

A matcher can be used in the call to With(...) when stubbing or expecting… an example could be setting an expectation that a search function on our user repository will return an empty result… like so:

In the example above, Is is a class containing a static method StringContatining, which returns a matcher of a certain type. Now, when the test runs, and NMock needs to decide if an intercepted function call matches the expectation above, it will iterate though the given matchers, and call their Matches function, passing to it the actual argument as object o.

The matcher returned by StringContaining probably contains an implementation of Matches which looks something like this:

where _substring was probably set in the ctor of the matcher when it was constructed by the StringContaining function.

Now that leads me to my recent problem: I needed to pull out the actual argument given when the expected function call was performed. In my case the argument was a delegate, which I wanted to pull out, and then invoke it a few times with different arguments.

What I did was this:

This allows me to set up an expectation like this:

Now, after the code has been run, I have access to the delegate passed to the file service through snatcher.Object.

If someone knows a cooler way to do this, please do post a comment below. Until then, I will continue to think that it was actually pretty nifty.