Working with Windsor and ASP.NET MVC

In the previous post I showed how easy it is to install an IoC container at the system boundary of your ASP.NET MVC application and have it resolve everything from there.

But what I did not show, was where the container came from – in the example, the container just pops out of nowhere on this line:

So how can we implement GetContainerInstanceFromSomewhere()?

Well, I like to do it like this:

Isn’t that easy? And then I have a folder structure in my ASP.NET MVC project that looks like this:

config-folder

It can be seen that I have a folder for each configuration of the system (development, test, prod) and one containing configuration files that are common for all configurations. For each configuration I have a hibernate.cfg.xml to configure NHibernate and a windsor.config which is loaded by the Windsor container in each particular configuration.

My development/windsor.config looks like this:

It can be seen that my development configuration is used to Cassini running on port 1766 🙂 moreover, it can be seen that my development configuration is using a fake, logging email sender, which – much as you would expect – only logs the content from emails that would otherwise have been sent.

Of course, the configuration files will not automatically be available to the web application the way they are organized now – therefore, my web project has a post-build task with the following two lines:

– thus copying the common configuration files along with the development configuration files to the base directory of the web application.

This also means that my build script must overwrite the development configuration files when building the system in a deployment configuration. It can be achieved as simple as this (using MSBuild):

Here I have define tasks for compiling the web site (“build”), deploying the binaries + views + content files (“deploy”), deploying common configuration files (“deploy_common_configuration_files”), and then one task for each deployable configuration: “deploy_test” and “deploy_prod”. This makes deploying the web site on my test web server as easy as running the following command:

What is left now, is to make sure that the different sets of configuration files are valid in the sense that Windsor can resolve everything right. That is easily accomplished in the following NUnit test:

This way, if I introduce a service in my development configuration that should have been implemented by a production version of the service in my production configuration, I will immediately know about it.

I think this post covers an easy and pragmatic way to control multiple configurations with Windsor and ASP.NET MVC. Of course you might want to split out the configuration-specific parts into multiple files instead of having only a windsor.config for each configuration. What I mean is something like this:

The great thing is that we can refactor our configuration with confidence because of our test. And if we want to be extra-certain that everything works as expect, we might begin to add assertions like this:

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.

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.