ArchitectureMidMCQ
What is Dependency Injection and why is it important?
Test your knowledge:
Explanation & Code
Answer: Dependency Injection (DI) means a type receives its dependencies from outside rather than creating them internally. This makes code testable, modular, and easier to change.
Code Example:
// ❌ Without DI — hard to test, tightly coupled
class OrderService {
private let network = NetworkClient() // created internally
private let db = Database()
}
// ✅ With DI — inject dependencies
class OrderService {
private let network: NetworkClientProtocol
private let db: DatabaseProtocol
init(network: NetworkClientProtocol, db: DatabaseProtocol) {
self.network = network
self.db = db
}
}
// Production
let service = OrderService(network: NetworkClient(), db: Database())
// Testing — inject mocks
let service = OrderService(network: MockNetwork(), db: MockDatabase())
Three types:
- Constructor injection — via
init(preferred) - Property injection — via settable property
- Method injection — via function parameter
Rate your understanding: