Angular › Dependency Injection Providers & Injection Tokens

How does the useFactory provider option let you create a service with more complex setup logic?

Advanced

Answer

The useFactory option lets you provide a function that Angular calls to create the actual value, rather than just instantiating a class directly, useful when creating a service requires some conditional logic or depends on other injected services first.
export function loggerFactory(config: AppConfig) {
  return config.verboseLogging ? new VerboseLogger() : new SimpleLogger();
}

providers: [
  { provide: LoggerService, useFactory: loggerFactory, deps: [AppConfig] }
]
Real-world example An app provides either a detailed, verbose logging service or a simple, minimal one depending on a configuration setting, using a factory provider to decide which specific implementation to actually create at startup.

Common follow-ups: What does the deps array in a factory provider actually specify?;When would useFactory be preferred over simply writing conditional logic inside the service's own constructor?