- Published
- Author
- Adithya HebbarSystem Analyst
How Dependency Injection Works in NestJS
NestJS uses Dependency Injection (DI) to manage the creation and lifecycle of classes like services, repositories, and providers. It leverages TypeScript's metadata to resolve dependencies automatically.
π How It Works:
β’ Declare Providers: Services and other classes are marked with
β’ Register Providers in a Module
β’ Use the Service via Constructor Injection
NestJS reads the constructor types and injects the required instances for you. No manual instantiation needed!
β Benefits:
β’ Decouples components
β’ Simplifies testing with mocks
β’ Promotes cleaner, modular code
#nestjs #dependencyinjection #typescript
NestJS uses Dependency Injection (DI) to manage the creation and lifecycle of classes like services, repositories, and providers. It leverages TypeScript's metadata to resolve dependencies automatically.
π How It Works:
β’ Declare Providers: Services and other classes are marked with
@Injectable() to make them available for dependency injection. They are then registered as providers in a module.TypeScript
// user.service.ts
@Injectable()
export class UserService {
getUsers() {
return ['Alice', 'Bob'];
}
}β’ Register Providers in a Module
Code
// user.module.ts
@Module({
controllers: [UserController],
providers: [UserService],
})
export class UserModule {}β’ Use the Service via Constructor Injection
Code
// user.controller.ts
@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) {}
@Get()
findAll() {
return this.userService.getUsers();
}
}NestJS reads the constructor types and injects the required instances for you. No manual instantiation needed!
β Benefits:
β’ Decouples components
β’ Simplifies testing with mocks
β’ Promotes cleaner, modular code
#nestjs #dependencyinjection #typescript