Tuesday, February 26, 2013

Advanced constructor injection with Autofac

Autofac is a great dependency injection framework where lots of features get on with ease of use. However configuring constructor parameters sometimes is not trivial.

Lets imagine following requirement: we need to inject NLog logger into our component and set logger's name according to our component type. Simple but arguable solution is to inject implementation of service locator pattern, namely Nlog's LogFactory class, but it introduces repeatable code and clogs our components with extra responsibility of creating loggers for themselves.

Good news is that it is possible to group functionality for creating loggers into a single place and inject right logger straight into constructor. Consider following component class:
It is marked by custom attribute of TypedLoggerAttribute type which means that logger should be injected into constructor. Configuration of injected logger is implemented as an Autofac module: This module will prepare preconfigured loggers for all constructors of target components. Use following code to see how it works: