Note: this article is published on 06/28/2024.
These will be a series of articles about Design Patterns. We start from MVC Pattern:
- Design Pattern (0), Overview
- Design Pattern (1), MVC
- Design Pattern (2), MVVM
- Design Pattern (3), Singleton
- Design Pattern (4), Desposal
- Design Pattern (5), Dependency Injection --- this article
A - Introduction
.NET supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies.This article will introduce the Dependency Inversion Principle first, then discuss the implementation of the principle: Dependency Injection.
- A - Introduction
- B - Dependency Inversion Principle
- C - Dependency Injection
B - Dependency Inversion Principle
The Dependency Inversion Principle states that High-level modules should not depend on low-level modules. Both should depend on abstraction.
The direction of dependency within the application should be in the direction of abstraction, not implementation details. Most applications are written such that compile-time dependency flows in the direction of runtime execution, producing a direct dependency graph. such as,
- Run Time: if class A calls a method of class B and class B calls a method of class C, then
- Compile time: class A will depend on class B, and class B will depend on class C
Shown as:

Applying the dependency inversion principle allows A to call methods on an abstraction that B implements, making it possible for A to call B at run time, but for B to depend on an interface controlled by A at compile time (thus, inverting the typical compile-time dependency). At run time, the flow of program execution remains unchanged, but the introduction of interfaces means that different implementations of these interfaces can easily be plugged in.

Dependency inversion is a key part of building loosely coupled applications, since implementation details can be written to depend on and implement higher-level abstractions, rather than the other way around. The resulting applications are more testable, modular, and maintainable as a result. The practice of dependency injection is made possible by following the dependency inversion principle.
C - Dependency Injection
Dependency Injection (DI) design pattern is a implementation for achieving Inversion of Control (IoC) between classes and their dependencies.
Strong coupled classes:
A dependency is an object that another object depends on. Examine the following MessageWriter class with a Write method that other classes depend on:





Join the conversation! Your thoughts help the community grow.