Default vs Autofac Dependency Injection Container in .NET

Dependency Injection (DI)

Dependency injection involves providing a class with its required dependencies from an external source rather than having the class create them itself.

This helps to decouple the object creation process from the caller, leading to a more modular and flexible system.

If you want to read in details you can check my LinkedIn Post

Dependency Injection Container

Dependency Injection Container is a kind of framework to add dependencies of application

It implements DI automatically and effectively

It manages creation and lifetime of dependency

It automatically disposes the dependency on right time

You don’t need to worry about object creation and taking care of disposing

Default DI Container Implementation and Issues

Suppose we have a service named NewsletterService and interface INewsletterService. Let’s see how can we add its Dependency Injection in default container.

Default vs Autofac Dependency Injection Container in .NET Core 6.

It works fine for simple applications but for complex applications where we have a lot of dependencies it can creates following issues

  • Lacks multi-tenant support
  • Lacks lazy Instantiation
  • Can’t handle dependencies effectively for big applications

What is Autofac and its Benefits

Autofac is DI Container for .NET , famous among DI Containers and solves above mentioned issues.

  1. It’s easy to use and learn

  2. Helpful in resolving dependencies for complex applications where size and complexity grows over the time.

  3. Great documentation

  4. Lot of helpful material already available

How to use Autofac in .NET Core 6.0

Step 1 : Install following Nuget Packages

Autofac (7.0.1 latest) with 212M Downloads

Autofac.Extensions.DependencyInjection (8.0.0 latest) 83M Downloads

Step 2 : Configure it in Program.cs

We have two approaches to do this either with Autofac Module or Directly within Program file.

Method 1 : Split Code in Different Module ( I love it)

Default vs Autofac Dependency Injection Container in .NET Core 6.

Method 2 : Put dependencies in Program.cs and overload the file :(

Default vs Autofac Dependency Injection Container in .NET Core 6.

This article was originally published at https://mwaseemzakir.substack.com/ on .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place