首页 > javascript > 请求范围服务

请求范围服务 (Request-Scoped Services)

问题

根据我的理解,现在nestjs在应用程序启动时创建了所有服务,也许我使用它是错误的是有没有办法配置NestJs根据请求创建服务?就像每次请求完成一样,会重新创建一些在该请求上使用的服务?

解决方法

随着nest.js 6.0的发布,增加了注入范围。有了这个,您可以为您的提供商选择以下三个范围之一:

  • SINGLETON:默认行为。您的提供程序的一个实例用于整个应用程序
  • TRANSIENT:为每个注入它的提供者创建一个专用的提供者实例。
  • 请求:对于每个请求,都会创建一个新的提供者。警告:此行为将在您的依赖关系链中冒出来。示例:如果UsersController(Singleton)注入注入OtherService(Request)的UsersService(Singleton),则UsersController和UsersService将自动成为请求范围。

用法

将它添加到@Injectable()装饰器:

@Injectable({ scope: Scope.REQUEST })
export class UsersService {}

或者在模块定义中为自定义提供程序设置它:

{
  provide: 'CACHE_MANAGER',
  useClass: CacheManager,
  scope: Scope.TRANSIENT,
}

问题

From what I understood now nestjs creates all the services when the application starts, maybe I'm using it wrong is there a way to configure NestJs to create services based on request? Like each time a request is done some services which are used on that request are recreated?

解决方法

With the release of nest.js 6.0, injection scopes were added. With this, you can choose one of the following three scopes for your providers:

  • SINGLETON: Default behavior. One instance of your provider is used for the whole application
  • TRANSIENT: A dedicated instance of your provider is created for every provider that injects it.
  • REQUEST: For each request, a new provider is created. Caution: This behavior will bubble up in your dependency chain. Example: If UsersController (Singleton) injects UsersService (Singleton) that injects OtherService (Request), then both UsersController and UsersService will automatically become request-scoped.

Usage

Either add it to the @Injectable() decorator:

@Injectable({ scope: Scope.REQUEST })
export class UsersService {}

Or set it for custom providers in your module definition:

{
  provide: 'CACHE_MANAGER',
  useClass: CacheManager,
  scope: Scope.TRANSIENT,
}
相似信息