How to use new instance for every new HTTP request

2019-07-24 21:41发布

问题:

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.

I'm using following code:

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

    constructor() {}

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

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

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.

Any guidance will be much appreciated.

Thank you.

回答1:

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

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.

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.