NG.IV · Angular 22 practice question
A library author is building a reusable module and needs to expose a configurable service. They are debating between providing a static configuration object versus using a provider function pattern. According to modern Angular best practices, what is the primary advantage of using the provider function approach?
Check answer and explanation
Correct answer: It allows the library to hide its internal implementation details while still allowing consumers to customize behavior using composition patterns.
Explanation
The provider function approach ensures that "Internal tokens and implementation details remain private" while enabling flexible composition.
Common trap
The guarantee that "the service will always be instantiated only once, regardless of how many components request it" describes singleton behavior, which is often desired but not the unique benefit highlighted by using provider functions over direct configuration. The claim that "it simplifies the build process by automatically optimizing all dependency imports at compile time" relates to build optimization, which is not the focus of this DI pattern.
Source: Angular docs: Defining dependency providers — Why use provider functions instead of direct configuration?
Checked against the cited text on 2026-11-25.