实例变量在Nestjs Singleton中值相同吗?

发布于 2025-01-21 18:54:46 字数 492 浏览 0 评论 0原文

因为Nestjs使用 singnleton Provider整个范围默认应用程序的提供商,实例变量如何管理?我想知道每个方法执行的实例变量是否相同。

也就是说,是否会因应在执行之间应隔离的变量而将其汇用?

import { Injectable } from '@nestjs/common';

@Injectable()
export class CatsService {
  private foo: any;

  someMethod() {
    this.foo = 'Initial value';
    // other changes here
    this.foo = 'Final value';
  }
}

As the Nestjs uses singleton provider pattern, hence shares a single instance of the provider across the entire application for scope Default, how the instance variables are managed? I wonder if the instance variables are the same for each method execution.

That said, would it be state-conflicted for variables which are supposed to be isolated between executions?

import { Injectable } from '@nestjs/common';

@Injectable()
export class CatsService {
  private foo: any;

  someMethod() {
    this.foo = 'Initial value';
    // other changes here
    this.foo = 'Final value';
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

聚集的泪 2025-01-28 18:54:47

是的,foo对于服务中的所有方法调用将相同,鉴于服务是单件范围(除默认值以外,还有请求和暂时范围),并且您尚未重新列出> catsservice在另一个模块中。您可以导入导入的模块&出口catsservice,它仍然是单身人士。

如果您希望在服务中的隔离上下文切换到请求或瞬态示波器,这将为您提供请求/瞬态范围示波器变量。免责声明:表演将受到打击。我亲自测试了差异,发现最坏的情况下,HTTP请求的平均值需要2倍的日志仪完成,最好的情况是平均请求完成下降了18%。您的里程可能会有所不同。

我测试的应用程序是一个不错的中型产品应用程序,具有I/O密集操作,而不是计算密集型操作。所有提供商都要求示范。

Yes, foo will be same for all the method calls in the service, given that, the service is singleton scope (there is request and transient scope other than default) and you have not redeclared the CatsService in another module .You can import the module that imports & exports CatsService and it will still be singleton.

If you want isolated contexts in your services switch to request or transient scopes, which will give you request/transient scoped variables. Disclaimer: The performance will take a hit. I have personally tested the difference and found that at worst, the average HTTP request took 2x logner to complete and the best case was 18% decrease in average request completion. Your Mileage may vary.

The App I tested was a decent mid size prod app with i/o intensive operation than a compute intensive one. All the providers were Request Scoped.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文