Trifork Geek Nights

Just wanted to say that I will be speaking at a couple of Trifork Geek Nights in November and December, about Castle Windsor and NServiceBus respectively.

First,

Advanced Windsor-Tricks

A quick introduction followed by some of the more advanced features of my favorite IoC container. If you’re new to IoC, or you are wondering what the fuzz is about, or you are interested in letting your container do some more work for you, you should come to this one 🙂

Will be held on

from 4:30 pm to 6:30 pm.

And then,

Distributed systems in .NET with NServiceBus

Introduction to messaging in .NET with NServiceBus. Will give an introduction to some fundamental messaging patterns and go on to show how these can be put to use with NServiceBus.

If you’re new to IoC, you can probably benefit from showing up at the “Advanced Windsor-Tricks” geek night before going to this one, because NServiceBus is relying heavily on having a container.

Will be held on

from 4:30 pm to 6:30 pm as well.

Hope to see some enthusiastic coders there.

PS: The Geek Nights will be held in Danish 🙂

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…?)

IoC component registration

An interesting topic, that I always love to discuss, is how to find a balance between building a pure domain model and being pragmatic and getting the job done. It just so happens, that getting the job done, and being able to add features to a system quickly, usually conflicts with my inner purist, who really wishes to keep my domain model and services oblivious of everything infrastructure-related.

Usually, I go for pragmatism. Not only because I’m lazy, but also because I think it’s funny to come up with solutions that accelerate development, and generally make the sun shine brighter.

Actually, this post should have been #2 in a series called “Polluting My Domain”, and this post should have been #1, because in #1 I showed how I usually use attributes to give hints to the automapper in Fluent NHibernate – e.g. [Cascade] on a relation to configure NHibernate to cascade operations across that relation, or [Indexed("ix__something")] to make that column be indexed in the database, or [Encrypted] to make that particular property be backed by an encrypting IUserType.

This post, however, will show a pragmatic, elegant and flexible way to make component registration easy in an IoC container.

Most IoC containers that I know of can be configured with XML and through some kind of more or less fluent API in code. I’ll spare you the XML, so I’ll just show a small example on Castle Windsor’s fluent API:

or you can perform multiple registrations like this:

This is all fine and dandy, but I think the fluent API becomes pretty complicated when you throw customized registrations per customer and/or environment into the mix – mostly because it will become kind of obscure which services get registered where.

Therefore, one of the first things I have put in my recent projects, have been a registration routine based on attributes. Pretty simple, and yes, it does pollute my domain services with infrastructure-related stuff, but this is a great example where I prefer pragmatism and simplicity over purity.

My most recent project has two attributes, ServiceAttribute and RegisterInAttribute that look something like this:

and then the registration code looks like this:

So, having established the current value of environment, my component registration will look like this:

– and that’s it! But the best of it is that adding services to the system now becomes a breeze – check this out – registering a concrete type, offering itself as a service:

– and here’s registering different stuff depending on the environment:

This way of registering component has proven to me several times to be a simple and nifty way of managing the differences between environments, and even differences between customers (which would require a few extensions to the example above though), still being able to add services to the system quickly.

Another benefit is that it’s pretty clear what happens, even to developers who might not be that experienced in using IoC containers. If I were the only developer on a project, I would probably prefer component registration based on conventions, but when you have a team, you sometimes need to make some things more explicit.

NServiceBus for dummies who want to be smarties 4

NServiceBus for dummies who want to be smarties 4… fourth post, this time on how to incorporate NServiceBus as a backend in an ASP.NET MVC application.

How to create the projects

First, create a new ASP.NET MVC project. I assume you know how to use an IoC container to instantiate controllers, and that you know how to configure your container (otherwise, there are plenty of information available – e.g. here and here), so I will just show this simple snippet on how to build the bus and put it in the container:

In Application_Start:

– and then the container can be created like this:

Notice the call to the extension method CastleWindsorBuilder? It comes from the assembly NServiceBus.ObjectBuilder.CastleWindsor.dll which is included with NServiceBus – it provides the adapters necessary for NServiceBus to a) register everything it discovers (like e.g. all your implementations of IHandleMessages<>), and b) pull instances when needed thus supplying dependencies during object activation. This way of supporting multiple IoC containers just plain ROCKS!

At this point NServiceBus has registered itself and registered all message handlers found in the current web application’s bin directory ( Configure.WithWeb() as opposed to Configure.With()) in the supplied IoC container, and since I am pulling all my controllers from Windsor, I can jump directly to implementing my HomeController:

As you can see, I implemented two actions responding to a HTTP post, both sending a message to the backend, but DoSomethingBad throws an exception, in which case i do not want the message to actually be sent.

My view is just a trivial (Spark) view with two forms:

And then I made a simple backend with one message handler:

Now, to check if things work, I navigate to /home/index, which on my computer looks like this:

dosomething

– and then I enter the text “WHEE!” into the first text field and press “Send”, yielding the following in my backend’s console window:

fantastic

Which is great! My backend receives messages from my web application, so now I can put all kinds of heavy calculations and processesing and whatnot in there, to be computed outside of web requests.

Now, what if something bad happens during the web request, and we do not want any messages to actually be sent? Well, if I enter a text into the other text field and submit it (to the DoSomethingBad action of my HomeController), nothing happens on the backend! Why is that?

Simply because I have started a TransactionScope in my controller layer supertype, TxBaseController, ensuring that all controller actions are run inside a (possibly distributed) transaction! It looks like this:

– and since message queueing plays along nicely with the currently ongoing ambient transaction (which e.g. the incredible NHibernate ALSO does), this transaction scope will make sure that everything just works!

Conclusion

That concludes today’s “NServiceBus for dummies who want to be smarties”. This one was on how to actually put NServiceBus to use as a simple backend for an ASP.NET MVC web application. Freaking easy, right?! Next time I will show how to put sagas to use by implementing one of the workflows of a typical web application.

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.

My favorite ASP.NET MVC hooks #1: Controller factory

My favorite hook in the ASP.NET MVC framework is the controller factory. I like it so much because it serves as a very simple entry point to the application, thus providing the perfect place to insert an IoC container. My container of choice is Castle Windsor – not because I have tried any other container – I really can’t say that I have – but because I just happened to be introduced by a colleague to Windsor, and I have yet to experience anything it can’t do for me!

An ASP.NET MVC controller factory is an implementation of the IControllerFactory interface – a simple interface with two methods: one that provides an IController given a string and some more stuff, and one that allows the controller to clean up any resources it might have allocated. The interface looks like this:

As you can see, it provides a means to return a controller, given all sorts of information about the current request and what could be resolved as the controllerName from the request URL.

ASP.NET MVC accesses the controller factory via the ControllerBuilder class – so if we want to provide our own controller factory, we must install the factory before any requests get served. An obvious place to do this, is the Application_Start method inside the global.asax.cs file. This way our controller factory will be installed every time the web application starts up.

The controller factory can be set in two ways: 1) By providing the type of the factory, and 2) By providing an instance of the factory. Then it’s up to you if you want to let ASP. NET MVC instantiate the factory. I usually do it like this:

– and let ASP.NET MVC instantiate and store a singleton instance of my factory.

My controller factory implementation looks like this:

Very simple. It takes the string, that was resolved as the controller name – e.g. “home”, “hOme”, “HOME” or whatever – and converts it to lower case, and then it uses that to look up a controller in my container. This means that all my controllers are registered in the container, and they will have all their dependencies automatically resolved when the container creates each instance.

A controller registration might look like this:

Simple – yet incredibly effective!

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.

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