Special Offer: My C#/.NET Bootcamp Course is out now. Get 10% OFF using the code FRIENDS10.

In this video, you’re going to learn about what dependency injection frameworks are and how they help your application’s dependency management. We take a look at the available dependency injection frameworks for the .NET platform. Next, we learn the fundamentals of Autofac.

Autofac is a well-known and frequently used dependency injection framework for the .NET platform. We also refactor an existing program to make use of Autofac in a sample application.

Content

0:31 Video Overview
1:28 What is a Dependency Injection framework?
2:35 Dependency Injection frameworks for .NET overview
3:18 Introduction to Autofac
5:15 Coding Activity: Integrate Autofac into an application

This video is part of the Dependency Injection playlist:

Subscribe to my channel, if you do not want to miss a video:

Transcript

The following part of this article contains the full transcript of the video for people who want to search the content or are not able to properly hear.

In this video, you’re going to learn about what dependency injection frameworks are and how they help your application’s dependency management. We also refactor an existing program to make use of Autofac, a dependency injection framework. Let’s jump into it!

Introduction

Hi, I’m a Software Engineer with more than 10 years experience on the .NET platform. My passion for learning and sharing knowledge as well as helping other developers improve are the reasons I started this channel.

Overview

First of all, this video builds upon the Introduction to Dependency Injection in C# video.

In case you are new to Dependency Injection, and you haven’t already watch that video you should watch it first. You find the link in the video description below. It will help you to understand the content and context of this video.

If you know about the fundamentals of dependency injection and want to learn about Autofac and how to use it, this video is what you want to see.

In the first part of this video, we are going to have a look at what a Dependency Injection framework is and which problem it solves.

Next, I will show you the major players in the C# space. There are many different frameworks available.

Furthermore, I will tell you what Autofac makes special and why I think it is a good fit for many applications and why it is very developer friendly.

In the last part of this video, I am going to refactor the application created in the first part of this series and integrate Autofac into an existing C# console application.

Dependency Injection Frameworks

A dependency injection framework helps you to manage your dependencies. It provides a central place often called the container which stores all your dependencies.

When your application needs an instance of a concrete class, it asks the container to provide one. Most frameworks also help you with the lifetime and the scope of your classes and provide additional features, for example, aspect-oriented programming.

Do we really need a framework for this? The idea behind a dependency injection framework is to make things simpler. It also provides additional features. For example, you can control how many instances of a specific implementation are created.

Could you do it all on your own? Yes, of course! But keep in mind that the main goal of your application is something different. It does not matter what the purpose of your application is; it’s probably not to write a lot of code dealing with code dependencies.

In the first video of this series, we learned that making use of dependency injection helps the structure and dependency management of your code, but you do not want to write all this code on your own.

Framework Overview

Now that we are convinced that a dependency injection framework might be useful to us let’s see which frameworks are available.

There are many different Dependency Injection frameworks for the .NET platform. Some of the better-known frameworks are Autofac, Ninject, Unity, and Structure Map.

Structure Map is the original dependency injection framework dating back to 2004 and is no longer recommended to use. The maintainers of the project recommend Lamar as an alternative.

Some other frameworks are Spring.NET, Castle Windsor, and, Simple Injector.

And there are many more frameworks.

You find a link in the video description to a good StackOverflow answer with an overview of most frameworks.

Autofac

Autofac is an open-source project hosted on Github and describes itself on their Github page as “a framework to manage the dependencies between classes so that applications stay easy to change as they grow in size and complexity.”

You find Autofac on its GitHub page linked in the description below or using your preferred search engine.

Autofac consists of a core package called Autofac and a series of additional packages. Those packages can be installed if you want to use additional features that are not part of the core framework or if you are going to integrate Autofac to a specific framework like ASP.NET Web API or many other popular frameworks.

Why Autofac? Autofac is my personal preference. I have not used all of the other mentioned frameworks. Instead, I have worked on small and big projects using Autofac, and I always got great results using Autofac.

The purpose of this short video is to give you a quick overview of dependency injection with Autofac and keep in mind that it is not possible to get into every detail of Autofac.

Now let’s take a look at the basic features we are going to use in our sample project.

Basic Autofac Features

Container

A container is a central place where all your registered dependencies live. It is the heart of your application as it has all the information required to create and manage instances of your classes.

Registration

A registration adds a dependency definition to the container. There are many different registration options. We will cover some of the basic registration methods in this video.

Module

A module helps you structure the registration of your dependencies. You can group registrations into modules and register the modules to your container. Modules help to structure the code especially in bigger applications which are built with modularity in mind.

Resolve

You can ask the container to create an instance of a specific type. The container resolves the dependencies, creates the instance and gives you a reference to the created object.

Code Refactoring

Now let’s take what we’ve learned so far, and apply it to our sample application. Remember the class diagram of our application currently looks like this:

Sample Application Class Diagram

We have an INotificationService interface with a single implementation called ConsoleNotification.

Next, we have a User class which has a reference to the INotificationService interface type and calls its NotifyUsernameChanged method in the ChangeUsername method.

The program class initializes the program and creates an instance of the User class.

And now let’s integrate Autofac.

Integrate Autofac

First, we need to add Autofac as a dependency to our project. We can do this using the NuGet Package Manager or using the Package Manager Console. The package is called Autofac, and we want to install the latest stable version which at the time of this recording is 4.8.1.

After the installation, we open the Program class. The first class we need is the ContainerBuilder class. Make sure to add a using statement for the Autofac namespace. The ContainerBuilder will create the Container using its Build method.

Next, we want to resolve the NotificationService using the Autofac container. Therefore, we create a notificationService variable and assign an instance of an object created by the Resolve method of the container.

We hit F5, the code compiles but we have a runtime exception of type ComponentNotRegisteredException with the exception message “the requested Service INotificationService has not been registered”.

Let’s head back to our Program class.

We created an instance of the ContainerBuilder class, and we created a Container by calling the Build method. Next, we want to resolve an instance of type INotificationService.

The problem is that we did not register our dependency to the container. Let’s fix this by registering the ConsoleNotification class as an implementation of the INotificationService interface. We can do this using the RegisterType method of the containerBuilder followed by the As-method. We register the ConsoleNotification type to be resolved whenever an instance of the type INotificationService is required.

Once again, we hit F5, start our application and finally we get the desired output in the console.

Create the UserService class

We want to go a step further and refactor our application. Currently, the User class does two things. It acts as a data class which is holding user information, and it calls the notificationService if the username is changed.

We create a new UserService class. We move the dependency to the INotificationService type and the ChangeUsername method from the User class to the UserService class.

We also need to remove the private setter of the Username property in the User class to make the setter visible to the UserService class. Next, we remove the INotificationService dependency from the User class. The User class is now a simple data class without any dependencies.

In the Program class, we need to change the call of the ChangeUsername method from the variable user1 to a userService variable. We initialize the userService variable using the container and resolve an instance of type UserService.

And yes – we need to register the UserService class to the container before we can create an instance. We do this by registering the UserService class as Itself. Registering a class as itself allows us to use the class type to resolve the type from the container. This register method can be used if the type you want to register does not implement an interface.

We start the application again, and we still see the same console output. Great!

Implement an Autofac Module

As a last change to the code for this video, we want to make use of Autofac’s modularity feature.

We create a new ProgramModule class. This class needs to extend the Module class from the Autofac namespace. We also need to override the Load method of the parent class.

The Load method receives a ContainerBuilder instance which we can use to register our dependencies. We can use the same methods as we did in the Program class. Therefore, we copy – paste the definitions from the Program class into our ProgramModule class and replace the variable name.

Back in the Program class we remove the copied dependency registrations and register the ProgramModule class instead using the RegisterModule method of the ContainerBuilder.

We hit F5 one last time, and we still see the same output in the console. Perfect!

Summary

In this video, we learned why and how dependency injection frameworks can improve the structure and the dependency management of our code.

Next, we learned the basic concepts of Autofac including containers, container builders, how to register dependencies and how to resolve types at runtime. In the last part of this video, we defined a module and registered it to the container.

That’s it. You now know the basic features of Autofac, and you can implement it in your own projects.

Next video

In the next video, we will dive deeper into Autofac, and we will learn a few advanced concepts which help you to create an even more maintainable and extensible application.

Please share your thoughts in the comments, give me some feedback and if you like this video, please hit the like button below and subscribe to the channel. See you in the next.

 

Claudio Bernasconi

I'm an enthusiastic Software Engineer with a passion for teaching .NET development on YouTube, writing articles about my journey on my blog, and making people smile.