Introduction
Providers and injection
Constructor injection, interfaces, scopes, tokens, async providers and test overrides.
A provider is any class the container builds for you: a service, a repository, a guard. It is built once (a singleton) unless you say otherwise, and handed to whatever asks for it.
Declaring and injecting
@Injectable
class UserService(private val repo: UserRepository, private val mailer: MailerService)
@Injectable(binds = [UserRepository::class]) // also available as the interface
class InMemoryUserRepository : UserRepositoryDependencies come from the constructor. The processor checks, at build time, that every one is provided by the module or an imported module, and that there are no cycles. A mistake is a compile error with a hint (which module provides it, which export is missing).
For a circular dependency, take one side lazily; the processor still checks it:
private val tokens: TokenService by inject()A nullable parameter (MailerService?) is optional: it is null when nothing provides it.
Parentheses are optional
@Injectable has defaults for everything it takes, so write it bare: @Injectable class UserService(...). Add arguments only when you need them: @Injectable(scope = Scope.REQUEST) or @Injectable(binds = [Mailer::class]). To inject configuration values into a provider, put @Value("key") on its constructor parameters.
Scopes
| Scope | Meaning |
|---|---|
Scope.SINGLETON | one instance (default) |
Scope.TRANSIENT | a new instance per injection |
Scope.REQUEST | one per HTTP request; may take HttpContext or HttpRequest; AutoCloseable ones are closed when the request ends |
A singleton that depends on a request-scoped provider becomes request-scoped itself (NestJS "scope bubbling").
Note
Limits
Request scope works for HTTP only, and guards and interceptors stay singletons. A type has one provider across the whole application (not one per module as in NestJS).
Tokens: injecting things that are not classes
val API_URL = Token<String>("api.url")
Kest.run<AppModule> { provide(API_URL) { "https://api.example.com" } }
@Injectable class Client(@Inject("api.url") private val url: String)Custom providers
| NestJS | Kest |
|---|---|
useValue, useFactory | provide<T> { r -> ... } in Kest.run<AppModule> { ... } |
useExisting | alias<A, B>() |
useClass | @Injectable(binds = [...]) |
async useFactory | provideAsync<T> { r -> future } or provideSuspend<T> { r -> ... } |
Kest.run<AppModule> {
provide<Mailer> { r -> Mailer(r.get(ConfigService::class).getRequired("smtp.host")) }
}Async providers
Some things must be ready before the application starts: a database pool, a remote configuration, a cache warm-up. Return a future (or write a suspend block) and the container waits for it while starting, so dependants always receive the finished value:
Kest.run<AppModule> {
provideAsync<SearchClient> { r -> SearchClient.connectAsync(r.get(ConfigService::class).getRequired("search.url")) }
provideSuspend<FeatureFlags>(timeout = Duration.ofSeconds(5)) { r -> loadFlags(r.get(HttpClientService::class)) }
}
@Injectable class Search(private val client: SearchClient) // sees a connected client- A failed future stops startup with the original exception, not a wrapper.
- A future that does not finish within
timeout(60 s by default) stops startup with a message that names the provider. - Under a
Token:provideAsync(TOKEN) { ... }. From Java:o.provideAsync(SearchClient.class, r -> ...). - Mark the type
@Providedso the build knows it is supplied at startup.
Creating and resolving by hand
Like NestJS's ModuleRef: inject Container and use
val parser = container.create(CsvParser::class) // builds a class that is NOT registered, taking constructor arguments from the container
val ticket = container.resolve(Ticket::class) // a transient provider: a new instance each call; a singleton: the shared onecreate uses reflection (the public constructor with the most parameters) and the object gets no lifecycle calls. Lazy-loaded modules are not supported.
Overriding in tests
override<T>(instance) replaces a provider; the testing helpers add overrideGuard, overrideProvider and friends.