LESSON 02 / 18·2 min readFoundation

Dependency injection

Try code in the playground
01 Understand02 Recall03 Prepare

Understand the concept

Dependency injection means a class receives the objects it needs instead of constructing them itself. Nest's container uses registered provider tokens to build and connect these dependencies. This centralizes construction and lets tests or configuration replace an implementation without rewriting its consumers.

Important ideas

  • A class asks for a dependency in its constructor.

  • Nest finds its provider token and supplies the registered instance.

  • This makes dependencies easier to replace in tests.

  • The @Injectable decorator supplies metadata, but the provider must also be available through the module graph.

Work through the example

TypeScript
import { Injectable, Module } from '@nestjs/common';

@Injectable()
class TaxService {
  calculate(amount: number) { return amount * 0.1; }
}

@Injectable()
class OrderService {
  constructor(private readonly tax: TaxService) {}
  total(amount: number) { return amount + this.tax.calculate(amount); }
}

@Module({ providers: [TaxService, OrderService], exports: [OrderService] })
class OrderModule {}
  • Nest constructs the registered services and supplies TaxService to OrderService.
  • The arithmetic is only a DI example; real money calculations need exact units and rounding rules.
PAUSE & RECALL

Can you explain it without the notes?

How does dependency injection work?

Use your own words. Explain an example and one limitation before checking the explanation.

Check your explanation

Dependency injection means a class receives the objects it needs instead of constructing them itself. Nest's container uses registered provider tokens to build and connect these dependencies. This centralizes construction and lets tests or configuration replace an implementation without rewriting its consumers.

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

  • Explain construction and replacement with a service/repository example rather than defining DI only as “using a constructor.”
Practice this concept
YOUR NEXT STEP

Keep connecting the ideas.

Next lesson: Why does Nest say it cannot resolve a dependency?

Adapted from 03_NESTJS.md · “How does dependency injection work?”. Examples are study fragments; framework behavior can depend on your version.