Dependency Injection (DI) is a design pattern that allows a class to receive its dependencies from external sources rather than creating them internally.
It’s part of the broader Inversion of Control (IoC) principle — meaning:
Instead of your class controlling its dependencies, something else (the DI container) provides them.
🔍 Simple Example (Without DI)
Problem:
-
NotificationServiceis tightly coupled toEmailService. -
If you want to switch to
SmsService, you must modify and recompile this class.
✅ With Dependency Injection
Now, the class depends on an abstraction (interface) — not a concrete implementation.
⚙️ How .NET Core Implements DI
.NET Core has a built-in dependency injection container — you don’t need external libraries like Autofac or Ninject (though you can still use them if needed).
You register your services in the Startup.cs (for .NET Core 3.1) or Program.cs (for .NET 6/7/8).
🧩 Example: Registering Services in .NET 6+
🧱 Service Lifetime Scopes in .NET Core
When registering dependencies, you choose their lifetime — how long they live in memory.
| Lifetime | Description | Example Use Case |
|---|---|---|
| Transient | Created each time they are requested. | Lightweight, stateless services. |
| Scoped | Created once per request (HTTP request). | Web API services, database context. |
| Singleton | Created only once for the entire app lifetime. | Configuration, caching, logging. |
Example:
🧩 How Dependencies Are Injected
.NET Core supports 3 injection methods:
| Type | Description | Example |
|---|---|---|
| Constructor Injection | Most common — dependencies passed via constructor. | public MyClass(IMyService service) |
| Method Injection | Dependencies passed directly into method. | void MyMethod(IMyService service) |
| Property Injection | Dependencies assigned to public property (less common). | public IMyService MyService { get; set; } |
💡 Example in ASP.NET Core Controller
And in Program.cs:
🧩 Real-Life Analogy
Think of DI like ordering coffee ☕:
-
You (the controller) need coffee (a dependency).
-
Instead of making it yourself (creating
new CoffeeMaker()), you ask the barista (DI container) to provide one. -
The barista knows which coffee maker to use (EmailService, SmsService, etc.).
-
You just consume it — no need to know how it’s made.
🧰 Benefits of Dependency Injection
✅ Loose coupling – Easier to swap implementations.
✅ Better testability – Mock dependencies in unit tests easily.
✅ Simpler maintenance – Fewer code changes when dependencies evolve.
✅ Centralized configuration – All service wiring is in one place.
✅ Improved scalability – Encourages modular architecture.
🧪 Example: Unit Testing with DI
No comments:
Post a Comment