Create an ASP.NET Core Web API and use Autofac for dependency injection

Prakash Kumar
5 min readJul 20, 2021

--

In this post, I will demonstrate how to build a Restful Web API using ASP.Net Core and use Autofac for dependency injection.

medium.com/@ananthomprakash

The Sections of this post will be as follows:

· What is dependency injection in asp.net?

· What is Autofac?

· How is Autofac better than Microsoft.Extensions.DependencyInjection?

· How to implement Autofac in our application?

If you are ready let’s get started

  1. Create an ASP.NET core web application

First, Open File-> New-> project in Visual Studio 2019:

2. Give name SampleWebApplication1

3. Choose .Net core 3.1 and click on create

4. At this point we have a starter project as follows.

5.Open startup.cs file and you can see default code.

You can learn more about startup.cs class and its structure in this link.

Now that we saw how to create a web api application. Let’s discuss what dependency injection is.

Dependency Injection (DI) is a software design pattern. It allows us to develop loosely-coupled code. The intent of Dependency Injection is to make code more maintainable. Dependency Injection helps to reduce the tight coupling between software components. Dependency Injection reduces the hard-coded dependencies between your classes by injecting those dependencies at run time instead of design time technically.

We typically use constructor dependency injection. To know more about dependency injection, refer this link.

Let us take a sample repository class called PostRepository.cs and its interface IPostRepository.cs

If we want to inject the dependencies of these classes in startup.cs using default dependency injection in ConfigueServices method you will write.

services.AddScoped<IPostRepository, PostRepository>();

Now let’s discuss how to implement the same using Autofac dependency injection.

1. What is Autofac?

Autofac is an inversion of control (IoC) container. If you’re not familiar with this idea, it’s a way in the object-oriented world to inject class dependencies (usually into a constructor). The purpose? Making it easier to test your code and centralizing the logic for dependency management.

2. It is an IoC container for Microsoft .NET. It manages the dependencies between classes so that applications stay easy to change as they grow in size and complexity. This is achieved by treating regular .NET classes as components.

3. So Autofac provides you with easy inversion of control, with the idea that this will keep your dependencies manageable and your code clean as it grows.

So, How is AutoFac better than Microsoft.Extensions.DependencyInjection?

It’s a question you usually get in interviews, the difference is in the additional features Autofac can offer you if you need them. For simple applications, the Microsoft DI may offer enough functionality. But as the application grows Autofac provides added features that you might want to use.

The features that Autofac additionally provides are:

1. Tagged lifetime scopes, and scoping services to those tags https://autofaccn.readthedocs.io/en/latest/lifetime/instance-scope.html#instance-per-matching-lifetime-scope

2. Resolving a service with some associated Metadata https://autofaccn.readthedocs.io/en/latest/advanced/metadata.html

3. Defining Named/Keyed variants of a service https://autofaccn.readthedocs.io/en/latest/advanced/keyed-services.html

4. Resolving a factory function you can use whenever you want https://autofaccn.readthedocs.io/en/latest/resolve/relationships.html#dynamic-instantiation-func-b

5. Lazy Instantiation https://autofaccn.readthedocs.io/en/latest/resolve/relationships.html#delayed-instantiation-lazy-b

Installing Autofac in your .Net Core project

Right-click on your project and select the NuGet package manager and install “Autofac” and “Autofac.Extensions.DependencyInjection” packages.

Add below Nuget packages.

Configure Autofac:

After the installation of Autofac packages, there are few steps to configure Autofac.

  1. Find the ConfigureServices method in the startup.cs file and change its return type from void to IServiceProvider.
  2. Add custom builder for Autofac register types and append with built-in IOC container. (see the below code)

public IServiceProvider ConfigureServices(IServiceCollection services)

{

services.AddControllers();

var builder = new ContainerBuilder();

builder.RegisterType<PostRepository>().As<IPostRepository>();

builder.Populate(services);

var container = builder.Build();

return new AutofacServiceProvider(container);

}

Here we added dependency using Autofac builder instead of default dependency injection.

Syntax to add dependencies using Autofac builder:

dependency injections for repository class

builder.RegisterType<Class>.As<IInterface>();

Registering Sql Connection with builder

builder.Register(c => new SqlConnection(Configuration.GetConnectionString)).As<IDbConnection>();

Now that we modified startup.cs class ConfigureServices method to use Autofac dependency injection we need to change program.cs class CreateHostBuilder method.

So, by default our program.cs file looks like this.

Here we need to modify CreateHostbuilder method like:

That’s it. We first added nugget packages related to Autofac then we modified startup.cs Configureservices method to use Autofac dependency injection and lastly, we modified program.cs class CreateHostbuilder from IHostBuilder to IWebHostBuilder.

We have seen how we can configure Autofac and replace the existing .NET core DI container.

Reference Link: Autofac’s Documentation

In the next article, I discuss on how to perform create, update, read and delete operations in the ASP.NET Core WEB API with Entity Framework Core.

I hope I’ve given you some basic understanding on how to use Autofac for dependency injection. If you like this post, a tad of extra motivation will be helpful by giving this post some claps 👏. I am always open to your questions and suggestions. You can share this on Facebook, Twitter, LinkedIn, so someone in need might stumble upon this.

Follow me on Twitter: https://twitter.com/realkumar07

Please do support me: https://www.buymeacoffee.com/realkumar07

Thanks for Reading!

--

--

Prakash Kumar

A software developer who loves to learn new things and share my knowledge with the world