Angular Dependency Injection | Types of dependency injection in Angular
Estimated study time: 9 minutes. The different provider strategies Angular's DI system supports.
Angular's Dependency Injection system isn't limited to just registering a class and letting Angular instantiate it. There are several provider types, each suited to a different scenario.
1. useClass — The Default
Tells Angular which class to instantiate when a dependency is requested. This is what happens implicitly with @Injectable({ providedIn: 'root' }).
providers: [{ provide: LoggerService, useClass: LoggerService }]
// Swap in a different implementation for testing or environments
providers: [{ provide: LoggerService, useClass: MockLoggerService }]
2. useValue — Providing a Fixed Value
Useful for configuration objects, constants, or mock data — anything that isn't a class you want Angular to construct.
export const APP_CONFIG = new InjectionToken('APP_CONFIG');
providers: [
{ provide: APP_CONFIG, useValue: { apiUrl: 'https://api.example.com', retries: 3 } }
]
3. useFactory — Computed at Runtime
Runs a function to produce the dependency, useful when the value depends on other injected services or runtime conditions.
providers: [
{
provide: LoggerService,
useFactory: (env: EnvironmentService) =>
env.isProduction ? new RemoteLoggerService() : new ConsoleLoggerService(),
deps: [EnvironmentService]
}
]
4. useExisting — Aliasing
Points one token to an already-registered provider, useful when you need two different injection tokens to resolve to the same instance.
providers: [
{ provide: NewLoggerService, useExisting: LoggerService }
]
Choosing the Right Type
| Provider Type | Best For |
|---|---|
| useClass | Standard services, swapping implementations |
| useValue | Config objects, constants, mocks |
| useFactory | Values that depend on runtime logic or other services |
| useExisting | Aliasing one token to another's instance |
useValue and useClass cover the vast majority of real-world cases — reach for useFactory only when the dependency truly needs to be computed dynamically.