wasAsked.

What is Dependency Inversion?

Impetus · Role not specified · technical

Published

Year not specified · .NET

Community answers

Posted by wasAsked editorial collection

The Dependency Inversion Principle (DIP) is the "D" in SOLID. It states: 1. High-level modules should not depend on low-level modules; both should depend on abstractions. 2. Abstractions should not depend on details; details should depend on abstractions. Without DIP: public class InvoiceService { private readonly SqlInvoiceRepository _repo = new(); // business logic depends on SQL details } InvoiceService (high-level business policy) is tied to a specific database implementation. Changing storage or unit-testing the service requires changing the class. With DIP: public interface IInvoiceRepository { Task SaveAsync(Invoice invoice); } // owned by the business layer public class InvoiceService(IInvoiceRepository repo) { /* uses the abstraction */ } public class SqlInvoiceRepository : IInvoiceRepository { /* EF Core details */ } Now the dependency points from the infrastructure detail towards the abstraction defined by the business layer — the direction is "inverted". The interface is designed around what the business needs, not around what the database offers. How it relates to similar terms: - Dependency Inversion is a design principle about the direction of dependencies. - Dependency Injection is a technique for supplying implementations (for example through constructors). - Inversion of Control is the broader idea that a framework or container controls object creation and flow. DI and IoC containers are common ways to apply DIP, but DIP is about how you design the abstractions. Benefits: - Business logic can be tested with fakes. - Infrastructure can change (SQL to Cosmos DB, SMTP to SendGrid) without touching rules. - It underpins Clean Architecture and Hexagonal (Ports and Adapters) architecture. Use it with judgment: abstractions are most valuable at volatile boundaries — databases, external APIs, file systems, time — not for every class.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics