Today I was setting up an infrastructure for a new project and I met the same problem I used to met couple times before - configuring injection of CommandDispatcher with decorators in Autofac don’t look well nor it’s easy to read. So I wrote extension methods to simplify future usage of decorators in Autofac.

## The Autofac way!

According to Autofac’s documentation the official way to register decorators looks like this:

It looks very messy and complicates registration of more sophisticated structures. What I especially don’t like is this line:

 (c, inner) => new TransactionalCommandDispatcher(inner),

If decorator has more dependencies than only decorated type this part of code will look terrible.

## How I want to do that?

I wanted to make the registration of many levels of decorators as simple as possible:

The only thing I need to do is to call method RegisterDecorated<TBase, TInterface> on builder, specify base type that will be decorated and interface of the type (and decorators). As parameters I can put any number of decorators. Decorators will be registered in the order specified in parameters.

And at the end when I’ll call dispatcher.Execute(cmd); I expect this call-stack:

## How to do that?

Simply, using similar approach that is suggested by Autofac documentation - registration of named types:

What is happening? I’m simply registering base type with name: {InterfaceTypeName}-0 (line 16) and following decorators as {InterfaceTypeName-i} (lines 18-30). Last decorator is registered as interface that will requested to be injected (lines 32-36). In this particular case it looks as follows:

Type   Name
CommandDispatcher -> ICommandDispatcher-0
TransactionalCommandDispatcherDecorator -> ICommandDispatcher-1
LoggingCommandDispatcherDecorator

If for some reason default value of keyBase (name of TInterace) don’t work in your case, you can easily specify other value during registration. In this approach all external dependencies will be resolved as usually at every level of this decorator chain.

The full code is available HERE.