What is dependency injection?medium

Type
design
Topic
solid
Frequency
common
Tags
solid
Answer

Dependency injection passes a class's dependencies from outside rather than having the class create them internally, making classes independently testable and loosely coupled.

Explanation

Instead of self.db = MySQLConnection() inside a class, inject it: def __init__(self, db: DatabaseConnection) . In tests, pass a mock. In production, pass the real implementation. Frameworks like Spring, FastAPI, and Angular provide DI containers that wire dependencies automatically.

Follow-upWhat is the difference between constructor injection and property injection?