如何在NestJS中为每个新的HTTP请求使用新实例? [英] How to use new instance for every new HTTP request in NestJS?

查看:940
本文介绍了如何在NestJS中为每个新的HTTP请求使用新实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个API,正在尝试发送请求.那是可行的,但我注意到收到响应后,这些类并未销毁.我目前正在使用nestJS,但在尝试测试时,nodeJS + expressJS也存在此问题.

I have an API and was trying to send a request. That is working but I noticed that the classes were not destroyed after I received a response. I'm working with nestJS at the moment but nodeJS + expressJS also had this issue when I tried to test.

我正在使用以下代码:

@Injectable()
export class UsersService {
    s = '';

    constructor() {}

    async findAll(): Promise<any> {
        this.s += ' haha ';
        return await this.s;
    }
}

这是第一次返回haha,第二次返回haha haha,依此类推.

This returned haha first time haha haha the second time and so on.

我不太确定这是否是所需的行为,或者可能配置不正确,因为我现在只是在学习nestJS.我以前曾与Zend Framework一起工作,但并未表现出这种行为.

I'm not really sure if this is the desired behaviour or may have not configured properly, because I'm just learning nestJS now. I have previously worked with Zend Framework which did not show this behaviour.

任何指导将不胜感激.

谢谢.

推荐答案

随着nest.js 6.0的发布,

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 :默认行为.您的提供商的一个实例用于整个应用程序
  • 瞬态:将为每个注入它的提供者创建一个专门的提供者实例.
  • 请求:对于每个请求,都会创建一个新的提供程序.警告:此行为会在您的依赖项链中冒出.示例:如果UsersController(Singleton)注入的UsersService(Singleton)注入OtherService(请求),则UsersController和UsersService都将自动成为请求范围的对象.
  • 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.

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

@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,
}


您正在寻找的是请求范围的提供程序. nest v5不支持它们,请参见此问题.到目前为止,所有提供者都是单例.


What you are looking for are request-scoped providers. They are not supported in nest v5, see this issue. As for now, all providers are singletons.

尽管它们是与此 pull请求一起添加的,并且它们将成为嵌套v6 .使用新版本,我们将获得临时范围和按请求范围.

They were added with this pull request though and will be part of nest v6. With the new version, we will get transient and per-request scopes.

这篇关于如何在NestJS中为每个新的HTTP请求使用新实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆