Sikau

NestJS · Day 3 · about 30 min

Providers and dependency injection

Services hold the logic; Nest wires them in.

Thin controllers, smart services

Controllers should only translate HTTP into calls. Business logic — finding dishes, calculating totals — lives in providers (usually *services*). And you never new them yourself: Nest creates one and injects it wherever it's asked for. That's dependency injection.

@Injectable and constructor injection

import { Controller, Get, Param, ParseIntPipe } from "@nestjs/common";
import { DishesService } from "./dishes.service";

@Controller("dishes")
export class DishesController {
  constructor(private readonly dishesService: DishesService) {}

  @Get()
  findAll() {
    return this.dishesService.findAll();
  }

  @Get(":id")
  findOne(@Param("id", ParseIntPipe) id: number) {
    return this.dishesService.findOne(id);
  }
}
  • A provider must be listed in a module's providers to be injectable there.
  • By default providers are singletons: one instance shared by everyone in the app.
  • DI makes testing easy: swap the real service for a fake one (later lesson).

The rest of this lesson

  • What the injector actually doesexplain
  • Why not just call new?explain
  • How many instances?predict
  • Startup orderorder
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of NestJS