Dependency injection — Autofac

Sławomir Kowalski
Aug 6 · 8 min read

Today, we go to the Autofac container description, in my opinion this container is the best :) when it comes to the .NET platform. Using the autofac container we can use virtually all the advantages that containers give us.


Autofac gives us all the advantages that I mentioned in the previous article. We can forget in the beginning about our container that we wrote. He does not reach autofac to his feet :) let’s see what’s so interesting about autofac. Let’s start with the basic logging and creation of class instances.

Easy, some say that Autofac is difficult, but here I prove that it is not true :)

Basic use of Autofac

This is the basic registration of classes in autofac.

And if we had these classes about 20 it would be a bit weak to rewrite each one. And in this we have the right approach 🙂

All we need to do is add something to the Main() function without registering each class in turn.

One condition must be such that the class we register is in the same project, that is, the class structure in the project must look like this:

We see that our project is ContainerConfig class. In this class, we have the Autofac configuration so that we do not have to do it in the Main function in order to have everything neatly organized.

We divide our classes that correspond with the main logic to a separate library and then we will see how to configure it, to get all dependencies automatically from a separate library. So, we’re going 🙂

Now our project for a total of two projects counting the library looks like this:

Now let’s see what the ContainerConfig class looks like.

As you can see in this class, we load dependencies from the library then we register all dependencies with interfaces and finally the GameServer class.

For this to work, we only need to call the Configure() method in the Main function :)

And everything is already working :)

Registering interfaces as Func

I promised in the previous article that I will explain what exactly is going with Func. The point is that we can register the relationship as Func and retrieve from the call of this registration some object that we need at a given moment. It will show you an example immediately

We have something in ContainerConfig class like this:

We have registered all dependencies and we have marked them using the Named() method, we can say that we have assigned these registers the keys through which below in Func registration we will create an instance of these registrations depending on the transferred key 🙂

In Func registration, we will create instances of the LoginValidator class, or singleton, or a new class depending on the key.

In the Main() function we have it 🙂

We provide Func to register the appropriate key and check which instance is singleton and which is a normal class.

The result is this:

Lifetime Objects

And how does it look with the lifetime of objects in Autofac?

There are three most important methods for managing the life of objects. Here they are:

I do not think I need to explain what this line above does :)

This method always creates a new instance object.

We will use the InstancePerDependency() method, which creates a new instance, but in each subsequent scope. I will show it on an example 🙂 It looks like this:

Such additional information 🙂 We do not need to register all interfaces, we can, for example, register the interfaces responsible for data validation, i.e. interfaces in the LoginPanel folder.

And in the Main () method we have something like this:

And in this way, we will create a new ICharacterSkillPoints interface instance in each new scope, but each subsequent creation of this class will end with assigning a previously created object :) Result :)

Circular dependencies

It is worth explaining the interrelationships, what if class A will depend on class B and class B will depend on class A? And this is the way 🙂

We have two sample classes in the WebServer class.

Suppose we want to get a number from the FirstClass class that is in the SecondClass class and from the SecondClass class the number that is in the FirstClass class. How can we do this? It is not that difficult. 🙂 Add ContainerConfig to the class:

So we need to call the .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies) method to allow dependencies and we need to register these dependencies as .InstancePerLifetimeScope() or .SingleInstance() we can not do this via the InstancePerDependency() object.

All we have to do is add the scope to the Main () function to make it work 🙂


But that’s not all the dependency refilling by constructors are not supported. When we add constructors to our classes:

We will get the exception:

Unless we put the constructor in only one of these two classes, then it will work well, good to know about that so that later we will not be surprised 🙂

In addition, it is worth mentioning that Autofac has a Dispose() method for cleaning the container that our container did not have.

Remember this :)


Another very nice thing about Autofac are interceptors that allow you to implement aspect programming. As I consider this approach an interesting solution, we will use it in our project 🙂

But what are interceptors? They enable capturing method calls by other components. We will use this to track the operation of our application so we will know when, what methods are called and what return.

To do this, let’s start with our ContainerConfig method and change some things there.

First, we need to register classes and mark them as interceptors. Then we need to register the CallLogger class in which we will call messages informing what is happening. Let’s see how it looks 🙂

In this class we display all messages.

But that’s not all we need to mark the class that we want to capture. And you can do it this way:

The same procedure with the PasswordValidator and LoginValidator classes.

At the end, create an ordinary scope in the client.

And we are happy how it works nicely, the result is this:

As you can see, the containers and Autofac are not so scary :)


Brilliant 🙂 This is more important things with Autofac is a bit of it 🙂 For the rest I refer to the documentation, which anyway is very good 🙂

My presentation on CQRS is approaching, so soon and on the blog it will be about CQRS and later it will be combined with dependency injection.

Link to github with the whole code from this article:

This content also you can find on my blog

As a standard, I remind you about the newsletter, which I send notifications about new entries and additional information about the IT world in general.

And NECESSERILY join the DevmanCommunity community on fb, part of the community is in one place

– site on fb: Kowalski

– group on fb: DevmanCommunity

Ask, comment underneath at the end of the post, share it, rate it, whatever you want :)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade