DEV Community

Brian H
Brian H

Posted on

Is it possible to have a service only used by an AuthGuard in the same module be a singleton?

I haven't been able to get it to work. It seems like the constructor of the auth guard is only called once, but I get a different instance of the service when canActivate is called in the guard.

Is there a way to confirm this? Is there a thing I can log to get the instanceId of the service or something?

Top comments (1)

Collapse
 
dvaswegen profile image
Duplessis van Aswegen • Edited

Does your Auth Guard have any dependencies? In nestjs services become request scoped automatically whenever any of their upstream dependencies are also request scoped.

Guards should be singletons otherwise, if not there might be some additional circumstances I'm unable to guess at unfortunately.

If the constructor is only called once, the guard should be a singleton. What makes youbelieve you're getting a different instance each time?