Software → Software Design
Dependency Injection
A technique where an object receives its dependencies from the outside instead of creating them itself.
Motivation
Dependency Injection solves the problem of objects constructing and controlling too much of their environment. Instead of creating dependencies internally, an object receives them from the outside.
Where it fits
Dependency Injection belongs to software design and is closely related to interfaces, dependency inversion, testing, and clean architecture.
Mental model
A class should focus on its job, not on building every collaborator it needs. Injection makes collaborators explicit.
TypeScript example
class OrderService {
constructor(private emailSender: EmailSender) {}
}
Python example
class OrderService:
def __init__(self, email_sender):
self.email_sender = email_sender
Common mistakes
- Thinking Dependency Injection requires a DI container.
- Injecting too many dependencies into one class.
- Using DI to hide poor boundaries instead of improving design.