🧩 The “D” in SOLID — Dependency Inversion Principle (DIP)
Dependency Inversion Principle (DIP) is the design principle behind the idea of Dependency Injection.
🧠What DIP States
High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend on details. Details should depend on abstractions.
In simpler words:
- Instead of classes depending on concrete implementations, they should depend on interfaces or abstract classes.
- This makes the system more flexible and loosely coupled.
🧱 Example Without DIP (Bad Design)
Problem:
- NotificationService depends directly on a concrete EmailService.
- If you want to switch to SmsService, you must modify NotificationService.
✅ Example With DIP (Good Design)
Now:
- NotificationService depends on the abstraction IMessageService.
- You can easily switch between implementations (Email, SMS, Push).
✅ This is Dependency Inversion Principle in action.
🧩 How Dependency Injection (DI) Fits In
Now that we understand DIP as a principle, here’s where DI comes in:
| Concept | What it is |
|---|---|
| DIP (Principle) | A guideline that says “depend on abstractions, not concretions.” |
| DI (Pattern) | A technique or mechanism to implement DIP in code. |
🔄 Relationship Between DIP and DI
Let’s visualize it:
So:
- DIP is about how classes should relate to each other (architectural rule).
- DI is about how to supply those dependencies (technical mechanism).
🧰 Example: Applying DI to Implement DIP
In .NET Core:
🧠Summary Comparison
| Aspect | Dependency Inversion Principle (DIP) | Dependency Injection (DI) |
|---|---|---|
| Type | Principle (part of SOLID) | Design Pattern / Technique |
| Purpose | To reduce coupling between high-level and low-level modules | To supply dependencies to classes at runtime |
| Focus | Architecture & relationships between classes | Implementation & object creation |
| Enforced By | Developer’s design | Framework or DI container |
| In .NET Core | Interfaces like IService, IRepository | AddScoped, AddSingleton, AddTransient |
💬 Analogy
| Concept | Analogy |
|---|---|
| DIP | “Don’t depend on specific brands; depend on a plug standard.” |
| DI | “Use a socket that provides power to any plug that fits.” |
🧾 Quick Recap
✅ DIP (Dependency Inversion Principle) = design principle (the “D” in SOLID)
✅ DI (Dependency Injection) = pattern / implementation of that principle
💡 DIP gives the rule, DI provides the tool to achieve it
No comments:
Post a Comment