| Muhammad Waseem

About Newsletter
Books
30 .NET Tips
Sponsorship
Default vs Autofac Dependency Injection Container in .NET
May 5, 2023
3 min read

Default vs Autofac Dependency Injection Container in .NET

Sponsor this Newsletter

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.

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<INewsletterService, NewsletterService>();

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)

using Autofac;
using AutofacDependencyInjectionContainer.Services;
public class AutofacModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<NewsletterService>()
               .As<INewsletterService>()
               .InstancePerDependency(); // Transient
        builder.RegisterType<LinkedInService>()
               .As<ILinkedInService>()
               .InstancePerLifetimeScope(); // Scoped
        builder.RegisterType<FacebookService>()
               .As<IFacebookService>()
               .InstancePerRequest(); // Scoped
        builder.RegisterType<LoggerService>()
               .As<ILoggerService>()
               .SingleInstance(); // Singleton
    }
}
...
using Autofac;
using Autofac.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
    builder.RegisterModule(new AutofacModule());
});
var app = builder.Build();
app.Run();

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

  using Autofac;
using Autofac.Extensions.DependencyInjection;
using AutofacDependencyInjectionContainer.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(container =>
{
    // Transient
    container.RegisterType<NewsletterService>()
             .As<INewsletterService>()
             .InstancePerDependency();
});
var app = builder.Build();
app.Run();
public class NewsletterService : INewsletterService
{
    public void SendNewsletter()
    {
        throw new NotImplementedException();
    }
}
..
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private readonly INewsletterService _newsletterService;
    public WeatherForecastController(INewsletterService newsletterService)
    {
        _newsletterService = newsletterService;
    }
    // Add your action methods here
}

This article was originally published at https://mwaseemzakir.substack.com/ on May 5, 2023 .

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
Previous Next

Subscribe to Newsletter

Join 9,000 Software Engineers

Buy Me a Coffee

Enjoy my articles? Support me by buying a coffee!

Buy Me a Coffee

Muhammad Waseem

Resources
  • Books
  • Courses
Newsletter
  • Articles
  • Sponsorship
Books
  • 30 .NET Tips
  • 100 .NET Tips (Soon)
Author
  • About Us
  • Contact Us
Policy
  • Privacy Policy
  • Terms and Conditions
Interview
  • C# & .NET
  • Web API

Join my .NET newsletter and stay updated!

© 2025 Muhammad Waseem. All rights reserved.