Anything Injectable Lives Here
Providers & Services
Providers are classes (usually services) marked with `@Injectable` that Nest can inject anywhere it manages.
What you'll learn
- Decorate a class with `@Injectable`
- Register it in a module's providers array
- Inject it via constructor parameters
Controllers are the doorways. Providers are everything behind the door — services, repositories, helpers, anything you’d want to inject. They’re where your business logic actually lives.
Defining a Service
import { Injectable } from '@nestjs/common';
export interface User {
id: number;
name: string;
}
@Injectable()
export class UsersService {
private users: User[] = [];
private nextId = 1;
findAll(): User[] {
return this.users;
}
create(name: string): User {
const user = { id: this.nextId++, name };
this.users.push(user);
return user;
}
} @Injectable() is the only ceremony — it marks the class so Nest’s DI
container will manage it.
Registering as a Provider
Add it to the owning module’s providers array. That tells Nest “I want
one of these, and you handle the lifecycle.”
@Module({
controllers: [UsersController],
providers: [UsersService],
})
export class UsersModule {} By default each provider is a singleton — Nest creates one instance and hands the same reference to everyone who asks for it.
Injecting via Constructor
Anywhere Nest creates the class for you (controllers, other providers, guards, interceptors), you can ask for a service in the constructor:
@Controller('users')
export class UsersController {
constructor(private readonly users: UsersService) {}
@Get()
list() { return this.users.findAll(); }
} Nest reads the parameter’s type at runtime (thanks to TypeScript’s
emitDecoratorMetadata), looks it up in the module’s providers, and
passes it in.
Why Bother Separating Service From Controller
The split is unglamorous but pays off:
- Testability — a service is a plain class, no HTTP context, trivial to unit-test.
- Reuse — the same service can back a controller, a CLI command, a queue worker.
- Swap-ability — at test time you can hand Nest a fake provider instead.
That last point is what the DI container buys you. Without it, every test becomes a wiring exercise.
Bootstrapping the App →