Dependency Inversion
Example
import { PostgresClient } from './postgres';
class OrderService {
private db = new PostgresClient();
async place(order: Order) {
await this.db.insert('orders', order);
}
}interface OrderRepo {
save(order: Order): Promise<void>;
}
class OrderService {
constructor(private orders: OrderRepo) {}
async place(order: Order) {
await this.orders.save(order);
}
}OrderService depends on the OrderRepo contract, so storage can change or be faked in tests.
Common mistakes
- Creating a database client inside a service, so the service can't be tested without a real database.
Key points
- Business logic receives its dependencies through the constructor or parameters, not
newinside it. - The interface is owned by the high-level module and named for its need, like
OrderRepo. - Tests pass a fake implementation instead of mocking module imports.
Interview questions
Dependency inversion vs dependency injection: what's the difference?
Inversion is the principle: depend on abstractions. Injection is a technique: pass dependencies in from outside, which is the usual way to apply it.
Do I need a DI container?
No. Passing dependencies through constructors or function parameters is enough for most apps; containers help only in large codebases.