Phelizer
Phelizer

Reputation: 319

Is it ok practice to use dependencies directly in NestJS

Is it ok to do something like this:

@WebSocketGateway()
export class BoardUpdateGateway {
  boardsService = new BoardsService();
  sectionsService = new SectionsService();
  tasksService = new TasksService();
  ...
}

Or should I inject dependencies like in nestJS docs examples, via constructor:

@Controller('boards')
export class BoardsController {
  constructor(private readonly boardsService: BoardsService) {}
}

Upvotes: 0

Views: 31

Answers (1)

Jesse Carter
Jesse Carter

Reputation: 21187

Dependency Injection promotes good code organization and testability which is why it is a popular design pattern across many different programming languages and frameworks. It's also part of the SOLID programming principles which are widely adopted inside the industry.

If at all possible you should inject dependencies in NestJS.

Upvotes: 2

Related Questions