#Is there a built-in way to use a Guard as singleton with UseGuards ?
8 messages · Page 1 of 1 (latest)
You can instantiate it yourself with guard = new MyGuard() and pass the instance to UseGuards. But that won't work with DI, so I don't think there's an easy way to do that without using an APP_GUARD
Technically you could add the original guard to a providers array and then have this new implementation use ModuleRef to get the original one, the new one is always a new instance but it retrieves the same actual implementation each time. Not really clean though
What's the use case you have for needing a singleton guard?
Thanks for the answers !
I'm confused by the last question though. Why does it need a new instance if
it's just a bunch of function without state ?
Technically, it doesn't need an instance. It can be an object that has a canActivate method on it that returns a boolean. That's technically the only stipulation
But often times, people inject services into the guard, soa class makes that easier than an object does, with Nest's DI system
Gotcha