A long while ago as I started with dependency injection and inversion of control, I started with the container the most people use at this time. Since a read a lot of Ayende I naturally started with Castle Windsor.
Now after a long time of using it, it dose not feel very well anymore. The registration interface is fluent, but looks ugly and it is not very clear what a lot of methods on the configuration interface do. At the end Windsor feels old and ugly (like it is with Monorail compared to MVC).
So to look at the other containers I have to define my requirements:
- It should be simple
- It should be extendable
- It should have a documentation
Now what containers are existing today. Here is a list of the most known ones with some initial thoughts on it.
- Large and cumbersome port from Java.
- Looks like a lot of things a never need
- Modern but I don’t like its over fluent interface (I don’t consider fluent interface which trying to build sentences very helpful)
- Small but it saw a lot of attributes on the sample code (don’t like to do all with attributes since CAB)
- The same about the fluent interfaces like StructureMap
- Small and very extendable codebase
- Interface looks simple and clean
So it seems Autofac is the right to try. And after using it now for some time, I really really like it.
Autofac has a clean and simple core which can be easily extended. And itself makes a lot of use of that. It have nearly all the functions that Windsor and the other containers have, but as extension to the core. Examples are XML configuration, ASP MVC, Proxy and a lot more. Autofac can create components with parameters from its type or position not only from its name like Windsor dose.
So how dose a simple registration looks like in Autofac?
var builder = new ContainerBuilder(); builder.RegisterType<MyComponent>() .As<IMyComponent>() .SingleInstance(); var container = builder.Build(); container.Resolve<IMyComponent>();
I also like the way you resolve multiple instances:
var assembly = Assembly.GetExecutingAssembly(); builder.RegisterAssemblyTypes(assembly) .Where(t => t.Name.EndsWith("Rule")) .As<IOrderRule>(); var container = builder.Build(); var rules = container.Resolve<IEnumerable<IOrderRule>>();
At the most it’s a matter of taste yes, but I can only suggest that you try it out yourself.