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 (2)

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?

Collapse
 
jerotas profile image
Brian H • Edited

Sorry for the late reply, I got busy with other things.

The Auth Guard only has 1 dependency, the AuthService. When I try to make the AuthService not static (and a singleton), the AuthService constructor gets called only once, on app startup. Then, I see when I call a method in the AuthService for the Guard, the object that was setup in the constructor is now null, so it's got to be another instance. I don't know why though.