Simple and pragmatic event bus with Castle Windsor

Almost always, when writing even the simplest of systems, the need arises for some kind of event publishing/subscription mechanism. There are of course many ways to achieve this, but I have found that Castle Windsor can provide everything that I need to build a simple, yet incredibly powerful event bus.

Consider this example from the real world: mortgage deeds follow many paths through our mortgage deed administration system, and one of them is purchase for the administrator’s own portfolio. Upon recording the purchase, it is crucial that the debtors are enlisted in our subscription at the Central Office Of Civil Registration (CPR in Danish), allowing us to receive updates whenever people change names or move without telling us.

A naive implementation of the Record method on the Purchase could look like this:

– but this is ugly! Enlisting the debtors has no direct relation to the logic of how to record a purchase, and when this requirement came, this implementation caused numerous tests to break. You could of course argue that our tests should not rely on the record method, but that was however the case, and it was a real P.I.T.A. to implement this.

Moreover, this approach forces us to grab our service locator inside a domain entity, which is really bad for too many reasons to mention here.

What we SHOULD have done, and what I have been doing ever since, is to create a simple event bus that resolves handlers to messages through Windsor (actually directly through the kernel because it is automatically injected). This way, I could have implemented the record method like this:

– and then this method would never change again (at least not for the wrong reasons)…

Then I have my simple event bus mediator (just an ounce of indirection, allowing my entities to be unaware of the service locator):

– which, depending on the bool inside the static EventBusConfiguration class, will be either a fake bus that swallows all its messages, or the real deal:

This means that subscribing to a message is as simple as registering implementations of this:

in my Windsor Container, e.g. the handler that enlists people in our subscription at the Central Office Of Civil Registration:

This is really cool, because it allows one to build systems where logic is deliciously decoupled, and you can add stuff, and then some more stuff, and the new stuff will not break the old stuff, because it doesn’t interfere with it.

Moreover, if you feel like extending it a little bit, it shouldn’t take that much of an effort to publish the events into a message queue for other systems to handle. If, for example, it took a while to process something, then I would definitely benefit from letting another process take care of that while my web request continues. Or if I wanted to update my data warehouse, I would build an aggregator in another process that did batch updates of the warehouse.

Oh, and this is one of the reasons that I would not hesitate to choose Castle Windsor if I were allowed to bring only one thing to a deserted island… you can build almost anything with a cool IoC container.

ASP.NET MVC – dependency injection by IoC container

One thing, that I have seen done wrong in so many ways, is DI in relation to ASP.NET MVC. Just to get things straight for everyone – including those, who have been living under a rock for the last 30 years – here’s a glossary:

  • Dependency injection (DI) – is exactly what it says, i.e. dependencies are injected. So your business methods don’t just instantiate order processors, they have them injected for them to use.
  • Inversion of control (IoC) – is when program flow is no longer just sequential. In many cases just a fancy term for a callback. In this case, it signifies that your classes may call stuff on instances on other classes, that are handed to them – which happens by DI.
  • IoC container – is a thing, that facilitates the above and removes the pain.

Quick, off the top of my head implementation of an ASP.NET MVC action method

Now what happens when we want to test this? Well, we definitely need the database to be there, otherwise we will probably get some nasty SqlException stuff happening. There may be other stuff going on, we don’t know. Or even if we know now, we will not have a clue in a few months! – because what if some class, on which our ProductService depends, changes? Or changes its dependencies? The product service is tightly coupled to everything that is architecturally beneath it. We need inversion of control!

Naรฏve IoC/DI example

Now, we have DI-enabled our service layer. It can be seen that the repository gets its NHibernate ISession from a session provider, that can probably be configured with a connection string somewhere. And we have a complex business rule inside a specification, and a service to use the repository and the specification together. This is much better, because all dependencies are explicit and injected from the outside. But this code is still not perfect – there’s way too much going on, the classes are all concrete, and there is no way to test the action method without instantiating all this stuff. And what happens when the product service is used in 100’s of places in the system, and suddenly it needs another specification in its constructor to decide whether the current user can be given a rebate? Damn! Back to work… let’s try again:

Service locator IoC/DI example

Now it’s much clearer again. But what is MyContainer? Well, it’s actually pretty simple: it’s a generic factory! And this time we are using the factory to supply a dependency when we need it and let the factory decide where to get it. Then it may deliver a new instance, an instance from a pool, an instance tied to the current HttpRequest or a singleton or whatever it feels like. This is the service locator pattern, and it’s better than the second example, but still – your code will be cluttered with calls to your container, so unit testing will not be as easy because your need to have a container in place or mock it.

This brings me to how to do it with ASP.NET MVC – the important thing is that we have one single call to container.Resolve<...>. We do it by taking control over how controllers are created, because the controller creation is the single entry point into as ASP.NET MVC application. Here goes:

ASP.NET MVC with IoC/DI

global.asax

MyControllerFactory.cs

And now – the best thing about DI: The class is pure! Look!

ProductsOnSaleController.cs

It is plain and simple, depending on a product service only, which gets automatically injected by the container. Easy to test, easy to extend. And we are probably going to write 100’s and 1000’s of action methods, so we are going to save a lot of work and grief on that account – thanks to DI and IoC.

I think this is THE way to do dependency injection in ASP.NET MVC controllers. I will show in another post how you can configure Castle Windsor with ASP.NET MVC to support multiple configurations (e.g. IEmailService is FakeLoggingEmailService on the developers’ machines and RealLiveSmtpEmailService in a production environment.

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.

Thoughts on metaprogramming

I’m not too much into long philosophical blog posts, but this is a great post by Raganwald about metaprogramming… Basically, he argues that tools that are powerful are also dangerous – but that should not keep you from using them. As an example he uses metaprogramming, because it is an extremely powerful feature of Ruby which can potentially be used in so many equally beneficial and/ or harmful ways.

Nifty web site with ASP.NET MVC

Sorry about the delay – I was interrupted by the new ASP.NET MVC release CTP 2 which came out last Wednesday or Thursday or something… I am currently working on updating the series to use CTP 2 instead of the first one… please be patient ๐Ÿ™‚

Update: Sorry, but I cancelled this series again. There so many tutorials on how to get going with ASP.NET MVC out there, so I will not finish this series. You should definitely check out Kazi Manzur Rashid’s blog – e.g. his two posts on best practices are brilliant: part 1 & part 2, and he has written a lot of other interesting stuff as well.

Nifty web site with ASP.NET MVC Part 2

[this post is outdated – too much has happened since the first CTP]

In this part of the ASP.NET MVC tutorial we will create our own controller factory which will use Windsor to resolve dependencies and supply each controller with a NHaml view factory. Then we will create some simple views and watch the whole thing in the web browser.
Read more

Nifty web site with ASP.NET MVC Part 1

[this post is outdated – too much has happened since the first CTP]

This is the first post in a series of at least four about ASP.NET MVC, which I am planning. The series will show a way to build a nifty web site with a tidy, sound, and scalable architecture. ASP.NET MVC will be used to structure the web site, Castle ActiveRecord will be used for persistence, Castle Windsor for dependency injection, NUnit and NMock for testing, NHaml for the views, and principles from agile, domain-driven design, and test-driven development will be used. The series assumes that you want to use the model-view-controller pattern, so I will not try to convince you that it is a great way to structure a web site ๐Ÿ™‚ – even though it is, and currently in my opinion the only sane way to make websites when they contain more than one page…

ASP.NET MVC is a part of the ASP.NET 3.5 Extensions, which is currently only available as a preview. Thus, the details might turn out to be a little off, but still most of the stuff we go through here will apply.

As this is the first post in the series, we will start out by creating a the solution and the project structure – just to get going.
Read more

A quick introduction to dependency injection using Castle Windsor

UPDATE: This post is pretty old. Please don’t use XML to configure Windsor, unless you’re aware of the nifty fluent registration API, but you absolutely need the runtime-flexibility that XML can offer.

A great pattern in software architecture is dependency injection (DI). It is a classical pattern apparently, but it seems to have become very popular again in TDD circles because of its obvious positive impact on testability. Moreover, I believe it is a healthy architectural exercise to structure your code to support DI, because it enforces separation of concerns.

Dependency injection can be explained like this: if X requires a Y to do its work, X does not create the Y by itself, it is given a Y to use. Thus, DI is an example of inversion of control (IoC), which is a fancy term for whenever you pass something for someone to call functions on.

In the following post, I will give a short example on how to practice DI using the Windsor IoC container.
Read more