Angular › Dependency Injection Providers & Injection Tokens
How does the useFactory provider option let you create a service with more complex setup logic?
AdvancedAnswer
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.