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.
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.
-
It’s easy to use and learn
-
Helpful in resolving dependencies for complex applications where size and complexity grows over the time.
-
Great documentation
-
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
}
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place