Fundamentals
Injection scopes
One instance for the whole application, one per request, or a new one each time.
The scope of a provider decides how many instances exist and how long each lives.
| Scope | Meaning | Use it for |
|---|---|---|
Scope.SINGLETON | one instance for the whole application (the default) | almost everything: services, repositories, clients |
Scope.REQUEST | a new instance for each HTTP request, shared by everything handled in that request | per-request state: the current tenant, a unit of work, request-specific caches |
Scope.TRANSIENT | a new instance every time it is injected | a small stateful helper that must not be shared |
@Injectable(scope = Scope.REQUEST)
class RequestAudit(private val request: HttpRequest) : AutoCloseable { // may inject the request or its context
val actions = mutableListOf<String>()
override fun close() { logger.info("request did ${actions}") } // called when the request ends
}
@Injectable class OrderService(private val audit: RequestAudit) // becomes request-scoped too (see below)Singletons are shared by many threads
A singleton serves many requests at the same time (each on its own virtual thread). So it must be thread-safe: keep no per-request data in its fields; use immutable values, concurrent collections or locks. If something genuinely belongs to one request, make it request-scoped or pass it as a parameter. See the concurrency model.
Scope bubbling
A singleton that depends on a request-scoped provider cannot be a singleton (it would hold on to one request's object forever), so it becomes request-scoped itself. This spreads up the chain: OrderService above is built per request because it needs RequestAudit, and so is anything that needs OrderService. The controller that uses it is built per request too. It works, but every request now builds those objects, so keep the request-scoped part small and at the edge.
Request values without request scope
If you only need to carry a request id or the current user to deep code, you often do not need a request-scoped provider: use RequestContext, which is cheaper.
Limits
- Request scope works for HTTP only (not queues, schedules or message handlers).
- Guards and interceptors stay singletons.
- A type has one provider across the whole application (not one per module as in NestJS).
- A request-scoped provider is closed (
AutoCloseable) when the request ends.