Member-only story

Dependency Inversion Principle VS Dependency Injection

Understanding the difference between the Dependency inversion principle and the Dependency injection using ASP.NET Core

Yohan Malshika
5 min readJan 3, 2024
Dependency Inversion Principle VS Dependency Injection

In the realm of object-oriented programming, the principles of Dependency Inversion (DI) and Dependency Injection (DI) play pivotal roles in achieving maintainable, scalable, and loosely coupled code. In C#, these principles are fundamental for writing robust and testable applications. Let’s delve into these concepts, understand their significance, and explore practical examples in C#.

Dependency Inversion Principle (DIP)

Dependency Inversion is a principle proposed by Robert C. Martin (Uncle Bob) as part of the SOLID principles. It suggests that 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 terms, this principle emphasizes:

  • Abstraction over concrete implementations: It promotes defining interfaces or abstract classes to decouple high-level modules from low-level implementation details.
  • Inverting the direction of dependency: Instead of classes depending directly on other concrete classes, they depend on interfaces or abstractions.

Consider a scenario where a BusinessLogic class directly depends on a DataAccess class:

public class BusinessLogic
{
private readonly DataAccess _dataAccess;

public BusinessLogic()
{
_dataAccess = new DataAccess();
}

// Methods using _dataAccess
}

This tight coupling makes the BusinessLogic class reliant on the DataAccess class, making it difficult to substitute or test different implementations of the DataAccess.

By adhering to the Dependency Inversion Principle, we can refactor this code:

public interface IDataAccess
{
// Method signatures
}

public class DataAccess : IDataAccess
{
// Implement methods
}

public class BusinessLogic
{
private readonly IDataAccess _dataAccess;

public BusinessLogic(IDataAccess dataAccess)
{
_dataAccess =…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Yohan Malshika
Yohan Malshika

Written by Yohan Malshika

Software Engineer | .Net Developer | Technical Writer

Responses (1)

Write a response

5 clips from me! I enjoyed reading your article. Thanks