π Understanding Dependency Injection in .NET — A Beginner-Friendly Guide
If you’ve worked with .NET, you’ve likely heard about Dependency Injection (DI). While it may sound technical, DI is simply a way of writing code that’s cleaner, easier to test, and more flexible.
Let’s break it down with real examples and explanations — including a working sample at the end.
π§ What Is Dependency Injection?
Imagine you’re at a coffee shop. Instead of making your own coffee, you just ask the barista — you depend on them to get the job done.
Similarly, in code, instead of creating your own objects, you ask a container (like a barista) to provide what you need.
That’s Dependency Injection.
π§ The Building Blocks of DI in .NET
.NET provides a built-in way to do DI through these components:
✔️ IServiceCollection
This is where you register the services your app will use.
✔️ IServiceProvider
This is the service factory that creates and delivers your services when needed.
✔️ ServiceDescriptor
A description of a service that includes:
-
The type (e.g.,
IGreetingService
) -
The implementation (e.g.,
DefaultGreetingService
) -
The lifetime (Singleton, Scoped, or Transient)
π Common Lifetimes
Lifetime | Description |
---|---|
Singleton | One instance for the entire app |
Scoped | One instance per request (in web apps) |
Transient | New instance every time it's requested |
π Real Example: DI in Action
Here’s a complete working example that shows how everything ties together:
π Let’s Break Down the Code
1️⃣ new ServiceCollection();
This creates a container where you register all the services your app will use.
2️⃣ services.AddSingleton<IConsole>(_ => new DefaultConsole { IsEnabled = true });
You are telling .NET:
"Whenever someone needs
IConsole
, give them this specificDefaultConsole
whereIsEnabled
is set to true."
This uses a lambda function to customize how the service is created.
3️⃣ services.AddSingleton<IGreetingService, DefaultGreetingService>();
This registers an interface-to-class mapping. If someone asks for IGreetingService
, they’ll get an instance of DefaultGreetingService
.
4️⃣ BuildServiceProvider();
This finalizes your service collection and builds a provider that can deliver services as needed.
5️⃣ GetRequiredService<T>();
This gets an instance of the service you registered. In our case:
-
IGreetingService
for greetings -
FarewellService
for goodbyes
π¬ Interfaces and Implementations Used
IConsole
and DefaultConsole
IGreetingService
and DefaultGreetingService
FarewellService
✅ Summary
-
Dependency Injection helps you build loosely-coupled, testable, and maintainable code.
-
.NET provides everything you need via
Microsoft.Extensions.DependencyInjection
. -
You register services with lifetimes and resolve them when needed.
-
Customizing services with lambdas allows for more flexibility — like configuring
IsEnabled
.
Comments
Post a Comment