Skip to content

Providers and Scopes

The three provider recipes and the four lifetimes in Typeix: shared, module scoped, request scoped and per injection point.

4 min read Source

A provider is a recipe that tells the injector how to produce a value for a token. Everything the injector hands out — services, the HTTP request, the logger, the router, a plain configuration object — is a provider. Understanding two dimensions covers the whole system: what recipe produces the value, and how long that value lives.

Tokens and recipes

A token is the key you inject by. It is usually the class itself, which is why the common case needs no strings:

@Injectable()
class UserService {
  @Inject() private logger: Logger;
}

A token can also be a string or a symbol when the value has no class — configuration, a connection, a constant:

providers: [
  {provide: "DB_URL", useValue: process.env.DATABASE_URL}
]
@Inject("DB_URL") private url: string;

There are exactly three recipes:

Recipe Produces Use it for
{provide: T, useClass: C} a new instance of C an interface-style token bound to one implementation
{provide: T, useFactory: fn} whatever fn returns anything that needs decisions or async work
{provide: T, useValue: v} v, untouched constants, mocks, existing objects

A bare class in a provider list is shorthand for {provide: C, useClass: C}, and a bare {provide: T} defers to the token's own class.

providers inside a provider are that provider's own dependencies, created first and handed to the factory:

{
  provide: "DB",
  useFactory: async (url: string, logger: Logger) => {
    const db = await connect(url);
    logger.info(`connected to ${url}`);
    return db;
  },
  providers: ["DB_URL", Logger]
}

useFactory may be async and useValue may be a promise — the injector awaits both. That is why pipeServer is asynchronous.

Scopes

The same recipe can be evaluated at four different lifetimes. This is the distinction that most affects correctness.

Scope Declared in Instances Typical use
Shared @RootModule({shared_providers: [...]}) one per application logger, router, config
Module @Module({providers: [...]}) one per module that provides it services owned by a feature
Request @Controller({providers: [...]}) one per HTTP request per-request state, a unit of work
Per injection point @CreateProvider(T) on the property or parameter a fresh one every time a short-lived helper, a builder
@Injectable()
class RequestScope {
  // created once per request, because the controller instance is per request
}

The scope is not a property you set; it is a consequence of where the provider is declared. A controller provider is request scoped because resty creates a controller instance per request from a child injector — see Request lifecycle.

@CreateProvider beats the hierarchy

Normally get() walks the injector chain and returns the first match, so you receive the shared instance. @CreateProvider skips that lookup and constructs a new one at the injection point:

@Injectable()
class ReportBuilder {
  @CreateProvider(Formatter) private formatter: Formatter;  // never shared
}

Use it when a provider is mutable scratch space. Do not use it to "be safe" — it defeats the point of a singleton and silently multiplies state.

Resolution rules

  • get(token) checks the current injector, then each parent. First match wins.
  • has(token) checks the current injector only. It is not a reachability test, which is why a child can get something it reports as absent.
  • A locally declared provider always wins over an imported one with the same token. Module merging keeps the local side, so re-declaring a service in a feature module deliberately gives that module its own instance.

Duplicate tokens throw

Providers are immutable by default: creating a second instance of the same token on the same injector raises an error rather than silently replacing the first. When replacement is intentional — a test double, a late override — list the token as mutable:

const injector = ModuleInjector.Sync.createAndResolve(Application, [], ["DB"]);

Choosing a scope

Question Answer
Does it hold no state, or only shared state? shared or module — one instance
Does it hold state that must not leak between requests? request scope (@Controller({providers}))
Does it need the current IncomingMessage / ServerResponse? request scope, and it cannot be a boot-time provider
Do you need a fresh instance on every use? @CreateProvider

Boot-time providers cannot depend on the request

providers on a module are instantiated during pipeServer, before any request exists. Injecting IncomingMessage into one fails at boot with No provider IncomingMessage. Declare it on the controller instead, or read the context — this is the same constraint that applies to GraphQL resolvers declared in providers.

Where to go next