Month: February 2017

Let’s say we’ve encapsulated an operation our application has to perform. I tend to write little classes which express the desired behaviour or which delegate to other classes if the need arises. An example of such an operation is the class illustrated here ‘UpdateCustomerCommand’.

In any application of reasonable size you end up with a lot of these classes. You want to keep these small and easy to read and keep any infrastructure out of the way. Let’s say we want to use transactionscope to manage the transaction, perhaps we’re connecting to a bunch of databases or reading from a message queue. You don’t want to modify all these command classes to add this behaviour. One solution is to introduce a base class which has this behaviour, but we all prefer composition over inheritance right? Let’s create a simple transactionalhandler.

This class is short and sweet and allows us to write this code once and not repeat it again and again. We just need to find a way to create the transactionalhandler and then pass in an instance of our class which does actual work as the inner handler. Enter AutoFac (or pretty much any IoC framework).

You can wire this up in AutoFac with the following code (copied and adapted from their website).

This approach is great if you have one cross cutting concern handler (like the transactionalhandler) and want to apply it to every implementation. There is no built in approach though if you want to apply this behaviour only to some classes. If you need more control you need to write some infrastructure code.

I introduce an attribute “NotTransactional” and apply it to some classes that I don’t want to take part in this decorator process. I then change the registration process.

I then loop trough every concrete class that implements the request handler interface and register them in the container.

The classes that will request the concrete handlers will always ask for an instance of the interface IRequestHandler with concrete request and response objects. The UpdateCustomerRequest for instance. So I register that type as well.

The registration mentioned above is done with a lambda. Whenever someone asks for an command handler we resolve the concrete implementation and if it wants to participate in a transaction we also ask for the transactional handler and pass our concrete handler to its constructor.

The same approach can be used to further decorate your commands. Adding a claims check can become pretty trivial.