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.
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)
Method 2 : Put dependencies in Program.cs and overload the file :(
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