Recently started working with a project that has a class called “UnityConfiguration” with 2000 lines of this
This fast becomes unmanageable, wait, I hear you say, not all Types are registered in the same way! Yes, and you won’t get away with a single line to wire-up your whole IoC container, but you should be able to get it way under 50 lines of code, even in big projects.
I prefer to go a bit Hungarian and file things via folders/namespaces by their types, then use the IoC framework to load in dependencies using this. This is because based on the Type is generally where you find the differences.
For example I put all my Attributes under a namespace called “Attributes”, with sub-folders if there is too many of course, as so on.
Below is an example of a WebApi application i have worked on in the past. This method is called assembly scanning and is in the Autofac doco here
var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterAssemblyModules( typeof(WebApiApplication).Assembly); containerBuilder.RegisterAssemblyTypes(typeof(WebApiApplication).Assembly) .Where(t => t.IsInNamespace("Company.Project.WebAPI.Lib")).AsImplementedInterfaces(); containerBuilder.RegisterAssemblyTypes(typeof(WebApiApplication).Assembly) .Where(t => t.IsInNamespace("Company.Project.WebAPI.Attributes")).PropertiesAutowired(); containerBuilder.RegisterAssemblyTypes(typeof(WebApiApplication).Assembly) .Where(t => t.IsInNamespace("Company.Project.WebAPI.Filters")).PropertiesAutowired(); containerBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); _container = containerBuilder.Build();
You can see form the above code that things like the Attributes and filters require the Properties AutoWired as I use Property injection as opposed to the constructor injection, as these require a parameter-less constructor. So I end up with one line for each sub-folder in my project basically.
So as long as I keep my filing system correct I don’t have to worry about maintaining a giant “Configuration” class for my IoC container.
You can also make use of modules in Autofac by implementing the Module, I recommend using this for libraries external to your project that you want to load in. you can use the RegisterAssemblyModules method in Autofac in a similar way