In an effort to keep code testable while adhering to the single responsibility and inversion of control principles, using an Inversion of Control (IoC) container like Autofac is a must. I have had a lot of fun working with this popular tool to handle all of my dependency injection. It works by holding all the object references in a static class, and it will build the dependency graph for you automatically. Then you just ask the container to resolve a type, and you have a fully instantiated object. This is much better than newing up the dependencies in the class manually because now I can easily create tests and inject mock dependencies for unit testing.

Lets first start by creating the container:

Setting up an Autofac container is straightforward, but there are a few options going forward you have when it comes to registering the types. Lets try a few ways and you can decide which one you prefer.

The easiest option is to add them one by on to the container:

This can become a big class if you are working with a large project.

Another way is to use reflection and enumerate through all the project’s assemblies and add them automatically:

There is some debate on if this is worth the performance hit of reflection, but it will only be ran on startup.

Another way is to delegate the responsibility to an Autofac module:

Then create a new class that inherits from the Autofac Module that is located within the project that has the types you wish to register.

This can be particular useful since you only wire up the main container once, and each project has an Autofac Module that is responsible for adding its own dependencies to the container.

As you can see it is pretty simple to set up Autofac within an application, and it helps you adhere to the Dependency Inversion Principle as stated in the SOLID principles of Object Oriented Design.

Here is a sample project from my github account
https://github.com/RyanOC/AutofacModules

Resources: