#onModuleInit called twice for singleton / DEFAULT scope provider

4 messages · Page 1 of 1 (latest)

fresh moon
#

Hi everyone,

I have created a module that exports a provider registered with the DEFAULT scope. In my app module I import this module, and also inject it into the ThrottleModule using the forRootAsync method. When I start up my app i see that the provider itself is created only once ( the constructor is hit only once ), yet the onModuleInit method and the onModuleDestroy method of the provider are invoked twice!

This is very confusing - I would assume that I could use the lifecycle methods to perform resource management, yet this doesn't seem to be the case. Please could someone shed some light on the issue? I have a minimal repo here: https://github.com/magoogli/nest-js

Any help would be most appreciated.

GitHub

Debug throttler. Contribute to magoogli/nest-js development by creating an account on GitHub.

trim whale
fresh moon
#

@trim whale What is best practice around managing a singleton instance then? If I have a singleton instance that say creates a connection or some resource, I need to clean that up. I Assumed ( apparently incorrectly ) that I could create the resource in the onModuleInit method and release it in the onModuleDestroy. If I cannot rely on these and I now create the resource in the constructor ( which NestJS invokes ) - how can I release the resource?