Why Dependency Injection
Separate construction from use for testability.
Why Dependency Injection
Dependency injection (DI) means giving an object the things it needs from outside, instead of letting it create them itself. This decouples components and makes them easier to test.
The Problem: Hard Coupling
When a type constructs its own collaborators, it is locked to those concrete classes and cannot be reconfigured or tested in isolation.
class Logger {
func log(_ m: String) { print("LOG: \(m)") }
}
class Service {
let logger = Logger() // hard-coded dependency
func run() { logger.log("running") }
}
Service().run()All lessons in this course
- Why Dependency Injection
- Constructor Injection
- Protocol-Based Abstractions
- Mocking Dependencies in Tests