Tuesday, June 29, 2010

Autofac Part 1 - ContainerBuilder: Simple registration

During my recent adventures, I've started looking into a IoC container an stumbled upon Autofac. The main problem are the lack of proper documentation, and that gives a somewhat bad impression, of a great IoC container.
Therefore I've decided to create some post about the different features present in Autofac, they are not meant to be a tutorial on how to use Autofac, only shed some light on the features Autofac provides.

The ContainerBuilder
One of the most important parts of Autofac, are the ContainerBuilder. It contains all the component registration, and has a lot of features.

Simple registration
Simple registration are easily, done by registering a type.
var cb = new ContainerBuilder();
cb.RegisterType<Abc>();
var c = cb.Build();
var a = c.Resolve<Abc>();

Simple interface registration
Registering a type as an interface, this are of course only allowed in the registered type implements the specified interface.
var cb = new ContainerBuilder();
cb.RegisterType<Abc>().As<IA>();
var c = cb.Build();
var a = c.Resolve<IA>();

External factory
When the container are disposed, all objects in the supplied by the container are also disposed. When using objects from a external factory, this may not be what you want, this is the reason why you can define that some objects shouldn't be disposed at the same time as the container.
var cb = new ContainerBuilder();
cb.RegisterType<Abc>().As<IA>().ExternallyOwned();
var c = cb.Build();
var a = c.Resolve<IA>();

Singleton
By default all dependent component or calls to Resolve, provides you with a new instance, but sometimes you want the same instance to be returned every time, just like a singleton.

var cb = new ContainerBuilder();
cb.RegisterType<Abc>().As<IA>().SingleInstance();
var c = cb.Build();
var a = c.Resolve<IA>();
var b = c.Resolve<IA>();
// a and b are the same object


Stay tuned for the next part where we take a look at registering ordering, keyed and name registration, and metadata.