Modern applications may easily manage dependencies thanks to.NET Core's built-in support for Dependency Injection (DI), a design pattern that facilitates the creation of loosely connected code. Using the IServiceCollection interface, we will examine how DI functions in.NET Core in this post and go over a basic example.
What Is Dependency Injection?
Dependency Injection is a technique where an object receives its dependencies from an external source rather than creating them itself. This makes the application easier to maintain, test, and scale.
Key Components in .NET Core DI
IServiceCollection
– Used to register dependencies (services).ServiceProvider
– Used to resolve dependencies.- Service Lifetimes
Singleton
: One instance for the application lifetime.Scoped
: One instance per request.Transient
: A new instance every time.
Example. Setting Up DI in a .NET Core Console Application
Let’s create a simple console app that demonstrates DI.
Step 1. Define Interfaces and Implementations
Step 2. Set Up DI with IServiceCollection
Explanation
AddTransient<IGreeter, ConsoleGreeter>()
: RegistersConsoleGreeter
as the implementation forIGreeter
. A new instance is created every time it’s requested.BuildServiceProvider()
: Compiles the service registrations into a container that can resolve services.GetRequiredService<IGreeter>()
: Requests an instance ofIGreeter
. The DI container automatically injects the correct implementation.
When to Use Which Lifetime?
Lifetime | Use When... |
---|---|
Singleton | Service should be shared for the app lifetime |
Scoped | Per web request (mostly in ASP.NET Core apps) |
Transient | Lightweight, stateless services |
Bonus: Use DI in ASP.NET Core
In ASP.NET Core, you don’t need to manually build the ServiceProvider
. Just use ConfigureServices
in Startup.cs
:
Then, inject via the constructor:
Dependency Injection in .NET Core is simple and powerful. Using IServiceCollection, you can register and manage dependencies with different lifetimes to keep your code clean and maintainable. Whether you're building a console app or a large web application, understanding and applying DI is a must-have skill in .NET Core development.
0 comments:
Post a Comment