Using Windsor as an auto-mocking container

One of my former colleagues blogged about using AutoFixture as an auto-mocking container the other day, which got me thinking about auto-mocking with Windsor.

Although I’ve never used auto-mocking myself, a few months ago, I answered a question on StackOverflow, hinting at how auto-mocking could be accomplished with Castle Windsor. I didn’t provide any example code though, so this post will show a more complete solution on how auto-mocking can be implemented with Windsor and Rhino Mocks[1. I realize that all the cool kids are using other mocking libraries these days. I’m still using Rhino though, but it should be a fairly trivial task to “port” this solution to another mocking library.].

A lazy component loader to generate the mocks

First, I create a simple ILazyComponentLoader that lazily registers a Rhino Mocks instance when a particular service is requested – like so:

– real simple. Windsor’s default lifestyle is singleton, which ensures that subsequent calls for the same service will give me the same mock instance.

Test fixture base class

Then I create a test fixture base class, which is supposed to act as exactly that: a fixture for the SUT:

As you can see, my SetUp method creates a new WindsorContainer, registering nothing but my AutoMockingLazyComponentLoader and TAppService – the SUT type. It then uses the container to instantiate the SUT, storing it away in a protected instance variable for test cases to work on.

I included DoSetUp and DoTearDown methods for my test fixtures to override in case they need to – but in most cases, they should not be used because of the coupling they introduce between test cases.

Lastly, I have two methods: Dep, which allows me to access an injected service type (short for “dependency”), and Mock which allows me to generate a new mock object in case I need to mock something other than my SUT’s dependencies.

How to write a new test fixture

As a result of this, a test fixture for something called HandleUpdateDisturbanceForecast is reduced to something like this:

– which I think looks pretty slick. And yes, this is an actual test case from something we’re building – doesn’t matter what it’s doing, just wanted to show an actual example.

It’s not like I’m saving a huge amount of coding here – I usually only instantiate my SUT in the SetUp method of my test fixtures, but I like how the “fixed style” of AutoMockingFixtureFor encourages application services to follow a pattern that makes for easy IoC and testing. And the fixture is relieved of almost all clutter that does not directly relate to the thing being tested.

Castle Windsor resolution logic: Cool handler filter that orders components

As you can see from my previous post on handler filters, an IHandlersFilter will have a chance to do stuff to the array of handlers that would otherwise be used untouched during a call to ResolveAll ( ResolveAll is also what happens behind the scenes when a component relies on CollectionResolver to supply a collection of components for it to use).

Now, what is left is to implement some kind of logic that does something to the handlers array. First thing that comes to my mind is ordering the handlers!

Ordering the handlers is very relevant e.g. in scenarios where tasks are modeled as a series of steps that should be executed in a consistent fashion. An example could be a component ( TaskProcessor) that gets a collection of implementations of some task-like interface injected ( IEnumerable<ITask>).

Now, to ensure that this list of tasks is properly ordered, I’d like to specify a few hints on how they should be ordered. Not too little, because otherwise stuff would not work, but I also don’t want to be overly explicit on how the tasks should be ordered.

So I came up with a solution based on two attributes: ExecutesBeforeAttribute and ExecutesAfterAttribute, allowing types to position themselves in relation to other types they know about, and all other types to stay oblivious of what is going on.

One possible usage scenario could look like this, assuming we have modeled some kind of money transfer as a series of steps, each implementing ITask:

and then a simplistic executor:

Now, carrying out a money transfer would consist of having the executor run through this list of discrete tasks, but it’s probably important that the validation occurs before the actual payment, and it probably doesn’t make sense to generate reports before the payment. Therefore, let’s decorate some of the steps:

and then make sure we respect them:

Now, when the container builds a TaskExecutor, it will inject the ITask implementations in the order specified by the attributes. Inside RespectOrderDirectivesHandlersFilter, there’s a HandlerSorter, which is the implementation of the actual sorting algorithm. It builds a directed graph out of components and their dependents, and then it orders the components so that they will be traversed in a way that respects the order specified by the attributes. I’m not an expert on graph algorithms, so I don’t know if my implementation is really really stupid and slow – but I know that a) it works, and b) the ordering is cached, so the algorithm will only run once per set of handlers.

If you want to know more, or perhaps put RespectOrderDirectivesHandlersFilter to use, you can visit the RespectOrderDirectivesHandlersFilter page on GitHub.

Castle Windsor resolution logic: Handler filters

One of the features I’m looking forward to in the upcoming Castle Windsor 3.0 (“Wawel”) release is handler filters! I’m especially looking forward to this feature because it solves a problem I have had quite a few times now, and also because it’s a feature that I’ve contributed to the Windsor project.

Please note that handler filter are NOT available before Windsor 3.0, which will probably be out sometime around middle August 2011.

As you can see, handler selectors is a hook in Resolve that sorts out the situation by choosing one handler among all the available handlers. Pretty much related to this, are handler filters, which is a hook in ResolveAll, that sorts out the situation by choosing and ordering several handlers from all the available handlers. Let’s take a look at a tiny example….

Example: Task processing pipeline

A golden use case for this feature is when you rely on CollectionResolver to inject a collection for you, e.g. in chain of responsibility-like scenarios like so:

Usually, when doing this kind of task processing, you care about the order in which the tasks are processed. Let’s pretend we have some tasks:

and the tasks are registered “dynamically” (allowing us to add new tasks just by dropping new implementations of ITask into the project), like so:

Now, how do we make sure that the PrepareSomething and FinishTheJob tasks are run at the right time, i.e. before and after CarryItOut? Handler filters to the rescue!

Let’s register a handler filter like so:

and the filter is implemented like this:

Now, when my program does this:

I get this output:

just as expected, which in turn means that CollectionResolver’s call to ResolveAll will also yield an ordered list of tasks.

One could also imagine that only certain handlers were returned, thus allowing tenants in multi-tenant scenarios to have different task processing pipelines.

Nifty, huh? In the next post, I will show a simple yet sophisticated way of ordering the handlers in the SelectHandlers method of a handler filter.

Castle Windsor resolution logic: Handler selectors

Do you know what handler selectors are? It’s a way for you to register some logic in Windsor that will choose among all the available handlers when some particular component is resolved.

E.g. if you have a multi-tenant application with multiple implementations of IUserNotifier, let’s call them NotifyUserBySms and NotifyUserByEmail, and you need to make sure that one particular tenant whose employees are equipped with smartphones get notified by email, you can let a handler selector make this selection transparent to the rest of your application by adding a handler selector, like so:

thus making it possible for all other services to depend on IUserNotifier, not caring under which tenant’s context they’re running.

As you can see, this handler selector only has an opinion when an IUserNotifier is being resolved. And then, when its SelectHandler method is invoked, it gets to choose among all assignable handlers for that particular service type, effectively providing a way to make sure that some particular implementation is used, given some condition (here simulated by some Console.ReadKey() action).

Nifty huh? Only sad thing though, is that handler selectors are not pulled from the container – you have to supply an instance to the kernel, so if you need some services in the selector you need to pull them manually from the container. This can of course be overcome by supplying the handler selector with a reference to the container, allowing it to Resolve stuff at will – just remember – as always – to Release what you Resolve.

This was a short introduction to handler selectors – next post will be about something new, namely handler filters which is a new feature in Windsor 3.0.

Free geek night about MongoDB

Goto ConferenceAt Goto Copenhagen this May, I gave a talk about MongoDB, which is a nifty document-oriented database that I find pretty interesting.

So, because I like to talk about MongoDB so much, I’ll give my talk again as a free Trifork geek night on Tuesday the 21th of June at the Trifork HQ in Aarhus (this time in Danish though).

If you’re a .NET person, possibly developing big enterprisey stuff and/or you’re interested in MongoDB or NoSQL in general, you should come to this one.

I’ll be speaking about MongoDB at GotoCph

I started playing around with MongoDB about a year ago, and since then I have grown to like it so much that I am going to try to tell what I know at the first ever Goto Copenhagen.

The talk is scheduled on the “Cloud and NoSQL” track on Thursday at 14:05.

A link directly to the abstract can be found here.

(PS: This is not an April fool’s day prank… :))

How to set the current culture in NServiceBus

Today we were experiencing some weird behavior when running an integration test with DillPickle, where – apparently – values of doubles would lose their decimal point when they were transferred in messages from our test to an NServiceBus service.

Stopping the service and inspecting the message in the queue quickly revealed a message that looked somewhat like this:

which is all fine and dandy.

Now, I’m used to being Danish, so I know that we’re somewhat deviant in regards to our decimal point – “,” – so we quickly diagnosed the problem: Our integration tests were running with the invariant culture, to allow us to parse Gherkin files in English and use “.” as the decimal point – but Windows and everything else was running with da-DK, so 13.56 would be improperly deserialized to the value 1356 when it reached our NServiceBus service.

Solution: Normalize the culture of all the processes of our system.

Our first attempt was to modify the culture in our endpoint configuration like so:

but obviously this did not work, because NServiceBus does not deserialize messages on this thread!

Our solution was to create a message module, which seems to get called before transport messages are deserialized, setting the culture in there – like so:

In the future I’ll make sure that the culture is explicitly set in all processes of systems I am building. It’s kind of scary that errors could happen where stuff like “debit account 100.00” could be mis-interpreted as “debit account 10000”!! 😮

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:

Nifty!

Tell, Don’t Ask

or “How big is an interface?”… Uuuh, what?

Well, consider these two interfaces:

– which is bigger?

If you think that ISomeService1 is the bigger interface, then there’s a good chance you’re wrong! Why is that?

It’s because an interface is not just the signatures of the methods and properties it exposes, it also consists of the types that go in and out of its methods and properties, and the assumptions that go along with them!

This is a fact that I see people often forget, and this is one of the reasons why everything gets easier if you adhere to the Tell, Don’t Ask principle. And by “everything”, I almost literally mean “everything”, but one thing stands out in particular: Unit testing!

Consider this imaginary API:

Now, in our system, on various occasions we need to change the values for a particular name. We start out by doing it like this:

Obviously, if GetValues returns a reference to a mutable object, and this object is the one kept inside the value store, this will work, and the system will chug along nicely.

The problem is that this has exposed much more than needed from our interface, including the assumption that the obtained Values reference is to the cached object, and an assumption that the Value1 and Value2 properties can set set, etc.

Now, imagine how tedious it will be to test that the Run method works, because we need to stub an instance of Values as a return value from GetValues. And when multiple test cases need to exercise the Run method to test different aspects of it, we need to make sure that GetValues returns a dummy object every time – otherwise we will get a NullReferenceException.

Now, let’s improve the API and change it into this:

adhering to the “Tell, Don’t Ask” principle, allowing a potential usage scenario like this:

As you can see, I have changed the API from a combined query/command thing to a pure command thing which appears to be much cleaner to the eye – it actually reveals exactly what is going on.

And testing has suddenly become a breeze, because our mocked ISomeKindOfValueStore will just record that the call happened, allowing us to assert it in the test cases where that is relevant, ignoring it in all the other test cases.

Another benefit is that this coding style lends itself better to stand the test of time, as it is more tolerant to changes – the implementation of ISomeKindOfValueStore may change an in-memory object, update something in a db, send a message to an external system, etc. A command API is just easier to change.

Therefore: Tell, Don’t Ask.

How Windsor’s decorators can save your life (almost)

Have you ever needed some kind of “master switch” in your application – i.e. some central place to flick a bool, resulting is changed behavior in numerous places?

Recently, we got the requirement that our application could function in two modes: active and passive. In active mode, the application must work like usual, whereas in passive mode, the app must not do anything to the outside world.

In our app, doing stuff to the outside world can be two things:

  • Writing stuff to a bunch of external SCADA systems.
  • Publishing status messages via NServiceBus.

which means that in order to implement passive mode, we need to avoid doing these two things.

Now, since everything in our app is wired by Windsor, and Windsor supports the nifty decorator pattern, implementing this “master switch” was a breeze!

The master switch

First, we implemented something like this to capture the switch itself:

which is registered like this:

Note th at the switch is a singleton, thus allowing all other services to have the same instance injected. Note also that concurrency is not an issue in our system – if MasterSwitch was to be used e.g. in an ASP.NET MVC application, it would have had a couple of locks in there or something similar.

Intercepting writes to external systems

All external hardware communication goes through an implementation of this interface:

so in order to abort all writes when we’re in passive mode, we added a new implementation of IExternalStuff that looks something like this:

Note how ExternalStuffWithMasterSwitch depends on IExternalStuff – this is where Windsor gets really cool, because if I remember to register my components in the following order:

then Windsor is smart enough to resolve the ExternalStuffWithMasterSwitch supplying the next available implementation of IExternalStuff, instead of entering a cycle.

Thus, we have cancelled all writes through IExternalStuff in our entire application with a few lines of extra code.

Avoiding publishing status messages

First, we needed som way to tell if a message was a status message, which was pretty easy – now all our status messages “implement” this marker interface which in turn implements IMessage from NServiceBus:

So, in order to “swallow” all published status messages when we’re in passive mode, we implemented this decorator to IBus:

which must be registered before NServiceBus’ own IBus gets registered:

I think this is a really cool example on how wiring everything with an IoC container provides some cool hooks in an application, allowing you to modify behavior in an extremely agile and non-intrusive manner.