Angular Factory Providers
Learn Angular Factory Providers in detail with useFactory, dependency injection, runtime configuration, InjectionToken, dynamic service creation, standalone APIs, architecture diagrams, enterprise examples, best practices, and interview questions.
Angular Factory Providers allow developers to create dependencies dynamically at runtime instead of always instantiating them directly.
Unlike useClass, which always creates a specific class, useFactory executes a factory function that determines what object or value should be returned.
Factory Providers are widely used in enterprise applications for:
- Runtime configuration
- Environment-based services
- Feature flags
- Authentication
- API configuration
- Logging
- Third-party SDK initialization
Understanding Factory Providers is an important Angular interview topic for Senior Developers, Tech Leads, and Architects.
Table of Contents
- What are Factory Providers?
- Why use Factory Providers?
- Factory Provider Architecture
- useFactory
- Factory Functions
- Dependencies (
deps) - InjectionToken with Factories
- Environment-Based Services
- Standalone Applications
- Enterprise Example
- Performance Best Practices
- Top 10 Interview Questions
- Summary
What is a Factory Provider?
A Factory Provider tells Angular to call a function to create a dependency.
Instead of:
providers: [
{
provide: LoggerService,
useClass: LoggerService
}
]
Angular executes:
providers: [
{
provide: LoggerService,
useFactory: loggerFactory
}
]
Angular calls loggerFactory() and injects its return value.
Why Use Factory Providers?
Factory Providers are useful when:
- Service creation depends on runtime values
- Multiple implementations are possible
- Environment-specific configuration is required
- Initialization requires external dependencies
- Configuration must be computed dynamically
Factory Provider Architecture
flowchart LR
Component
Component --> Injector
Injector --> FactoryProvider
FactoryProvider --> FactoryFunction
FactoryFunction --> Service
Service --> Component
Dependency Resolution Flow
sequenceDiagram
participant Component
participant Injector
participant Factory
participant Service
Component->>Injector: Request LoggerService
Injector->>Factory: Execute Factory
Factory->>Service: Create Service
Service-->>Component: Inject Instance
Basic useFactory Example
Factory
export function loggerFactory() {
return new LoggerService();
}
Provider
providers:[
{
provide:LoggerService,
useFactory:loggerFactory
}
]
Angular executes the factory function and injects the returned object.
Factory Execution Flow
flowchart TD
Injector
Injector --> Factory
Factory --> CreateService
CreateService --> Component
Factory with Dependencies
Factory functions can receive dependencies from Angular.
export function apiFactory(
config: ConfigService
){
return new ApiService(
config.apiUrl
);
}
Provider
providers:[
{
provide:ApiService,
useFactory:apiFactory,
deps:[ConfigService]
}
]
Angular resolves ConfigService first and passes it into the factory.
Factory with deps Architecture
flowchart LR
Injector
Injector --> ConfigService
ConfigService --> Factory
Factory --> ApiService
ApiService --> Component
Factory Returning Different Services
Suppose two logger implementations exist.
export class ConsoleLogger{}
export class CloudLogger{}
Factory
export function loggerFactory(){
if(environment.production){
return new CloudLogger();
}
return new ConsoleLogger();
}
Provider
providers:[
{
provide:LoggerService,
useFactory:loggerFactory
}
]
Angular injects the appropriate implementation depending on the environment.
Runtime Selection
flowchart TD
Factory
Factory --> Production
Factory --> Development
Production --> CloudLogger
Development --> ConsoleLogger
Factory with InjectionToken
Create a token.
export const APP_CONFIG=
new InjectionToken<AppConfig>(
'APP_CONFIG'
);
Factory
export function configFactory(){
return{
apiUrl:'https://api.company.com',
timeout:30000
};
}
Provider
providers:[
{
provide:APP_CONFIG,
useFactory:configFactory
}
]
Inject
config =
inject(APP_CONFIG);
Factory + InjectionToken Flow
flowchart LR
InjectionToken
InjectionToken --> Factory
Factory --> Configuration
Configuration --> Component
Runtime Configuration Example
export function appFactory(){
return{
production:true,
apiVersion:'v2',
enableLogging:true
};
}
Angular creates the configuration only when requested.
Authentication Factory Example
export function authFactory(
config:ConfigService
){
if(config.oauth){
return new OAuthService();
}
return new JwtService();
}
Provider
providers:[
{
provide:AuthService,
useFactory:authFactory,
deps:[ConfigService]
}
]
Authentication Architecture
flowchart TD
ConfigService
ConfigService --> Factory
Factory --> OAuthService
Factory --> JwtService
OAuthService --> Component
JwtService --> Component
Standalone Application Example
bootstrapApplication(AppComponent,{
providers:[
{
provide:APP_CONFIG,
useFactory:configFactory
}
]
});
Factory Providers work exactly the same in standalone Angular applications.
Enterprise Banking Example
A banking application requires:
- Payment Service
- Authentication
- Fraud Detection
- Logging
- Notifications
Factory
export function paymentFactory(
config:ConfigService
){
if(config.useSandbox){
return new SandboxPaymentService();
}
return new ProductionPaymentService();
}
Provider
providers:[
{
provide:PaymentService,
useFactory:paymentFactory,
deps:[ConfigService]
}
]
Enterprise Architecture
flowchart TD
RootInjector
RootInjector --> ConfigService
ConfigService --> PaymentFactory
PaymentFactory --> SandboxPaymentService
PaymentFactory --> ProductionPaymentService
ProductionPaymentService --> PaymentComponent
SandboxPaymentService --> PaymentComponent
Factory vs useClass
| useClass | useFactory |
|---|---|
| Creates a class directly | Executes a factory function |
| Static implementation | Runtime selection |
| Simple configuration | Dynamic configuration |
| Fixed dependency | Flexible dependency creation |
Factory vs useValue
| useFactory | useValue |
|---|---|
| Dynamic | Static |
| Runtime execution | Constant value |
| Supports dependencies | No dependencies |
| Configurable | Fixed |
Real-World Factory Provider Use Cases
| Scenario | Factory Provider |
|---|---|
| Environment-specific APIs | ✅ |
| OAuth vs JWT | ✅ |
| Payment Gateway Selection | ✅ |
| Feature Flags | ✅ |
| Cloud vs Local Storage | ✅ |
| Logging Strategy | ✅ |
| SDK Initialization | ✅ |
| Runtime Configuration | ✅ |
Performance Best Practices
| Practice | Benefit |
|---|---|
| Keep factory functions lightweight | Faster dependency resolution |
| Reuse injected services | Avoid duplicate work |
Use deps instead of manual creation |
Better DI integration |
Prefer InjectionToken for configuration |
Strong typing |
| Keep factories deterministic | Predictable behavior |
Use useClass when runtime logic is unnecessary |
Simpler provider configuration |
Common Mistakes
Creating Dependencies Manually
❌ Avoid
new ConfigService()
Instead
deps:[
ConfigService
]
Let Angular inject dependencies.
Large Factory Functions
Avoid putting business logic into factory functions.
Keep them focused on object creation.
Returning Different Types Unexpectedly
A factory should always return an object that satisfies the expected provider contract.
Forgetting deps
useFactory:apiFactory
If the factory requires dependencies, include:
deps:[
ConfigService
]
Best Practices
- Keep factory functions small.
- Use
depsfor dependency resolution. - Use
InjectionTokenfor configuration values. - Return objects that match the expected abstraction.
- Use factories only when runtime behavior is required.
- Prefer
useClassfor straightforward service creation. - Write unit tests for factory logic.
Advantages
| Feature | Benefit |
|---|---|
| Runtime Creation | Dynamic services |
| Dependency Support | Works with DI |
| Environment Aware | Multiple implementations |
| InjectionToken Support | Flexible configuration |
| Standalone Ready | Modern Angular |
| Enterprise Friendly | Highly configurable |
Top 10 Angular Factory Providers Interview Questions
1. What is a Factory Provider?
Answer
A Factory Provider uses useFactory to execute a function that creates and returns the dependency to be injected.
2. When should Factory Providers be used?
Answer
Use Factory Providers when dependency creation depends on runtime configuration, environment settings, feature flags, or other injected services.
3. What is useFactory?
Answer
useFactory is a provider configuration that instructs Angular to call a factory function instead of directly instantiating a class.
4. What is deps?
Answer
deps is an array of dependencies that Angular resolves and passes as arguments to the factory function.
Example:
deps:[
ConfigService
]
5. Can Factory Providers return different implementations?
Answer
Yes.
A factory can return different implementations based on runtime conditions such as environment or configuration.
6. Can Factory Providers work with InjectionToken?
Answer
Yes.
They are commonly used together to create dynamic configuration values.
7. What is the difference between useFactory and useClass?
| useFactory | useClass |
|---|---|
| Dynamic creation | Direct instantiation |
| Runtime logic | Fixed implementation |
| Supports conditional creation | Always creates the specified class |
8. Can Factory Providers be used in standalone Angular applications?
Answer
Yes.
They are registered using the providers array passed to bootstrapApplication() or in route-level providers.
9. What are common enterprise use cases?
Answer
- Environment configuration
- OAuth vs JWT selection
- Payment gateway selection
- Feature flags
- Cloud storage selection
- Logging configuration
- Third-party SDK initialization
10. What are the best practices?
Answer
- Keep factory functions focused.
- Use
depsinstead of manual object creation. - Use
InjectionTokenfor configuration. - Return consistent implementations.
- Use factories only when runtime behavior is required.
- Prefer
useClassfor simple scenarios. - Test factory logic independently.
Interview Cheat Sheet
| Topic | Remember |
|---|---|
| Provider | useFactory |
| Function | Factory Function |
| Dependencies | deps |
| Configuration | InjectionToken |
| Runtime Selection | Supported |
| Environment Aware | Yes |
| Standalone | Supported |
| Alternative | useClass |
| Static Values | useValue |
| Best Practice | Keep factories simple |
Summary
Angular Factory Providers enable dynamic dependency creation using useFactory. They are ideal when services or configuration depend on runtime conditions, environment settings, feature flags, or injected dependencies. Combined with InjectionToken, deps, and Angular's Dependency Injection system, Factory Providers provide a flexible and scalable way to configure enterprise Angular applications while keeping object creation centralized and maintainable.
Key Takeaways
- ✔
useFactoryexecutes a factory function to create dependencies. - ✔ Factory Providers support runtime decision-making.
- ✔ Use
depsto inject dependencies into factory functions. - ✔ Combine Factory Providers with
InjectionTokenfor dynamic configuration. - ✔ Return consistent implementations from factories.
- ✔ Keep factory functions lightweight and focused.
- ✔ Prefer
useClasswhen runtime logic is unnecessary. - ✔ Fully supported in standalone Angular applications.
- ✔ Factory Providers are widely used in enterprise architectures.
- ✔ A common Angular interview topic for senior developers.
Next Article
➡️ 37-useClass-useValue-useExisting-QA.md