All topics
Servicesadvanced

Factory Providers

Explain useFactory providers and when constructing a dependency requires logic beyond a simple class instantiation.

Most providers just map a token to a class Angular can instantiate directly, but sometimes constructing a dependency requires actual logic — reading a value from localStorage, choosing between two implementations based on a feature flag, or wrapping a third-party library's own initialization function. A useFactory provider handles exactly this case: instead of a class, you supply a function, and Angular calls that function (injecting whatever the factory itself needs via the deps array) to produce the value that gets registered against the token.

A useClass provider is like ordering a standard item off a menu; a useFactory provider is like giving the kitchen a custom recipe that combines several existing ingredients (deps) in a specific way before the dish is ready to serve.

Key Concepts

1
The deps array is important and easy to get wrong: it explicitly lists the tokens the factory function needs injected as its own parameters, in the same order the factory function expects them, since a plain function (unlike a class) has no decorator metadata Angular can inspect to infer its dependencies automatically.
deps
2
This pattern is common for environment-conditional services (return a mock implementation in development, a real one in production), for wrapping non-Angular libraries that need imperative setup before they're usable, and for APP_INITIALIZER-style bootstrap logic that needs to run some async work (like fetching remote configuration) before the app fully starts.
APP_INITIALIZER
3
Interviewers sometimes contrast useFactory with useClass and useValue: useClass swaps in a different class for a token (still using normal DI-driven construction), useValue provides a pre-built, static value directly with no construction logic at all, and useFactory is the escape hatch for everything in between that needs actual runtime decision-making to produce the right value.
useFactoryuseClassuseValue