Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 42 ยท Controllers and Routing

Providers and Dependency Injection

Understand NestJS providers, @Injectable and constructor injection, how the injector builds singletons, why DI helps testing, and how to avoid circular dependencies.

Controllers should be thin, so where does the real work live? In providers. A provider is any class that Nest can create and hand to other classes: services, repositories, factories, helpers. The most common provider is a service, a class marked with @Injectable() that holds business logic. A controller does not create its service. It simply declares that it needs one, and Nest supplies it. That is dependency injection, or DI, and it is the idea that holds the whole framework together.

In this lesson you learn how to write and register providers, how constructor injection works, what "singleton" means here, why DI makes testing easy, and why circular dependencies are a design smell. Real Nest code is read-only, and you can run a working mini DI container as a stand-in. Remember from How a Nest App Boots that the real container reads TypeScript constructor types, whereas our stand-in uses an explicit inject list.

A service and a controller

TypeScript
// cats.service.ts
import { Injectable } from '@nestjs/common';

@Injectable()
export class CatsService {
  private readonly cats = [{ id: 1, name: 'Tom' }];

  findAll() {
    return this.cats;
  }
}
TypeScript
// cats.controller.ts
import { Controller, Get } from '@nestjs/common';
import { CatsService } from './cats.service';

@Controller('cats')
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Get()
  findAll() {
    return this.catsService.findAll();
  }
}
TypeScript
// cats.module.ts
@Module({
  controllers: [CatsController],
  providers: [CatsService],
})
export class CatsModule {}

Three things make this work. @Injectable() marks CatsService as manageable by the container. The providers array in the module registers it. And the constructor parameter private readonly catsService: CatsService is a request: "give me the provider registered under the CatsService class". The private readonly shorthand also declares and assigns the property in one go. You never write new CatsService().

Dependency injection in three steps

Mark @Injectable() on the class.
Register Add it to a module's providers.
Inject Ask for it in a constructor.
1 / 2

What the injector does

At startup the container looks at each class, reads its constructor parameter types, and builds the dependencies first, recursively. By default every provider is a singleton: one instance for the whole application, created once and shared by every class that asks for it. That is why a service can keep an in-memory cache or a connection pool safely, and also why it must not store per-request data in properties. Singletons are shared by all concurrent requests.

This stand-in is a working miniature container. register records a class, resolve builds it and its dependencies, keeps one instance per class, and refuses to loop forever on circular dependencies.

Node.js A working mini DI container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the output. ClockService is built first, then CatsService, then the controller. The controller and the audit service share the same CatsService instance, so the cat added through the controller is visible to the audit service. The last two lines show a cycle being detected and the kind of message you meet in real Nest when a provider is not registered or not available in a module; see Modules for the exact rules.

Why DI helps testing

When a class asks for its dependencies instead of creating them, a test can hand it fakes. CatsService above reads time from ClockService, so a test can pass a clock that always returns a fixed value, a database that lives in memory, or an email sender that records messages instead of sending them. In real Nest this is done with Test.createTestingModule({...}).overrideProvider(CatsService).useValue(fake), covered in Testing Nest Applications.

Node.js Swapping a dependency for a fake

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

SignupService has no idea whether it received the real mailer or the fake. That is the whole benefit: the logic is tested in isolation, quickly, and without a network.

Circular dependencies

A circular dependency happens when A needs B and B needs A. The container cannot build either first. The mini container above reports it with the chain, and real Nest fails with an error as well. Nest does offer an escape hatch, forwardRef, which must be used on both sides:

TypeScript
@Injectable()
export class AService {
  constructor(@Inject(forwardRef(() => BService)) private b: BService) {}
}

@Injectable()
export class BService {
  constructor(@Inject(forwardRef(() => AService)) private a: AService) {}
}

Treat forwardRef as a last resort. A cycle usually means two classes know too much about each other. Better fixes are to move the shared logic into a third provider that both can use, or to talk through events (see Queues and Events). One related trap is file imports: if two files import each other, a class can be undefined when its decorator runs, and that is a plain JavaScript circular import, not a DI problem.

Providers are singletons by default, but they can also be created per request or per consumer. That changes performance and is covered in Dynamic Modules and Provider Scopes. Providers can also be registered in other forms (values, factories, aliases), which you will meet in Custom Providers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What are the three steps to use a service in a controller?

    @Injectable() marks the class, the module's providers array registers it, and a constructor parameter requests it.
  2. 2. What does 'singleton' mean for a Nest provider by default?

    Default providers have one shared instance for the whole app, so they must not hold per-request data in fields.
  3. 3. Why does DI make unit testing easier?

    Because a class receives its dependencies instead of creating them, a test can supply an in-memory or recording replacement.
  4. 4. What is the best way to deal with a circular dependency between two services?

    forwardRef works but hides a design problem. Moving the shared part elsewhere removes the cycle.

Summary

  • A provider is any class the container can create and inject; a service is a provider marked with @Injectable().
  • Register providers in a module's providers array and request them with constructor parameters.
  • By default a provider is a singleton shared by all consumers, so never keep per-request data in its fields.
  • The container builds dependencies first, in order, and fails at startup when one is missing or circular.
  • DI lets tests replace real dependencies with fakes, which is the main reason Nest code is testable.
  • Avoid circular dependencies by extracting shared logic or using events; forwardRef is a last resort.
  • Our mini container is a stand-in; the real one reads constructor types and supports scopes and custom providers.

Next: Modules