Fundamentals
Module reference
Look up and create providers by hand.
Normally a class gets what it needs in its constructor. Sometimes you must get a provider dynamically, by type chosen at run time, or create an object that is not registered. NestJS calls this ModuleRef; in Kest you inject the Container:
@Injectable
class ReportRunner(private val container: Container) {
fun run(kind: KClass<out Report>): String =
container.get(kind).render() // a registered provider, chosen at run time
fun parse(text: String): List<Row> {
val parser = container.create(CsvParser::class) // builds a class that is NOT registered, taking constructor arguments from the container
return parser.parse(text)
}
}| Call | Does |
|---|---|
container.get(Type::class) | the provider (a singleton: the shared one; a transient: a new one) |
container.getOrNull(Type::class) | the provider, or null when none |
container.resolve(Type::class) | like get, for transient providers: a new instance each call |
container.create(Type::class) | builds a class not registered anywhere, filling its constructor from the container |
container.load(Module::class) | registers a module after start-up (Lazy-loading modules) |
create uses reflection (the public constructor with the most parameters), and the object it builds gets no lifecycle calls and is not tracked by the container.
When (not) to use it
Prefer constructor injection: it is checked at build time and visible in the class. Reach for the container when:
- you pick an implementation at run time (a strategy chosen by a name in the request);
- a framework-style component needs to find providers, like a plugin system (also see the discovery service);
- you must create short-lived helper objects that take injected services.
A registry is often cleaner than the container: inject List<Strategy> or a map of providers and pick one.