All academies

Dependency Injection

Inject collaborators instead of creating them — loose coupling.

22 minLevel 15 of 20

The problem: tight coupling

When a class creates dependencies with new, it couples to concretes — hard to test and swap.

Without DI
class Database { query(sql: string) { return ["rows:" + sql]; } }
class UserRepository {
  private db = new Database();
  findAll() { return this.db.query("SELECT * FROM users"); }
}
console.log(new UserRepository().findAll());
console.log("Hard to fake Database in tests.");

Inject instead

Declare needs in the constructor. An assembler (you or IoC) provides collaborators. Depend on abstractions.

With DI
interface Database { query(sql: string): string[]; }
class InMemoryDatabase implements Database {
  query(sql: string) { return ["memory:" + sql]; }
}
class UserRepository {
  constructor(private readonly db: Database) {}
  findAll() { return this.db.query("SELECT * FROM users"); }
}
console.log(new UserRepository(new InMemoryDatabase()).findAll());

Nest constructor injection

Nest reads constructor types / tokens and injects registered providers. Open the DI Simulator for the visual contrast.

Nest-shaped
class OrdersRepository { find() { return [{ id: "o1" }]; } }
class OrdersService {
  constructor(private readonly orders: OrdersRepository) {}
  list() { return this.orders.find(); }
}
class OrdersController {
  constructor(private readonly orders: OrdersService) {}
  get() { return this.orders.list(); }
}
console.log(new OrdersController(new OrdersService(new OrdersRepository())).get());

Check your understanding

5 questions

Question 1 of 5

Score: 0

Multiple choice

DI means dependencies are: