Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ How Providers Work in Nest.js | Dependency Injection and Modules
Building Backend Applications with Nest.js

How Providers Work in Nest.js

メニューを表示するにはスワイプしてください

Previously, you learned that Nest.js can inject dependencies automatically. But how does Nest.js know which classes it can create?

To make a class available for dependency injection, you mark it with the @Injectable() decorator.

@Injectable()
export class UsersService {}

Next, register the service inside a module using the providers array.

@Module({
  providers: [UsersService],
})

Here is what is happening:

  • @Injectable() tells Nest.js that the class can be managed by the framework;
  • providers registers the service with the module;
  • Nest.js creates a single instance of the service;
  • Whenever another class requests UsersService, Nest.js provides the same instance automatically.

For example, the controller can now receive the service through its constructor:

constructor(private usersService: UsersService) {}

This system keeps your application organized by allowing different parts of your code to work together without manually creating or managing objects.

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 4.  2

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

How Providers Work in Nest.js

Previously, you learned that Nest.js can inject dependencies automatically. But how does Nest.js know which classes it can create?

To make a class available for dependency injection, you mark it with the @Injectable() decorator.

@Injectable()
export class UsersService {}

Next, register the service inside a module using the providers array.

@Module({
  providers: [UsersService],
})

Here is what is happening:

  • @Injectable() tells Nest.js that the class can be managed by the framework;
  • providers registers the service with the module;
  • Nest.js creates a single instance of the service;
  • Whenever another class requests UsersService, Nest.js provides the same instance automatically.

For example, the controller can now receive the service through its constructor:

constructor(private usersService: UsersService) {}

This system keeps your application organized by allowing different parts of your code to work together without manually creating or managing objects.

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 4.  2
some-alt