NestJS · Middle · Question 11 of 75
When would you use useFactory for a provider?
{
provide: "REDIS",
useFactory: async (config: ConfigService) => createClient({ url: config.get("REDIS_URL") }).connect(),
inject: [ConfigService],
}- 1Only in tests
- ✓Correct answer: When the instance must be created with logic or other dependencies, possibly asynchronously, e.g. a connected client
- 3Only for classes without dependencies
Explanation
Async factories delay app startup until they resolve, so the connection is ready before anything uses it.