Dependency injection
A service holds a store, which holds a log; the store is in memory for
the tests and in a database in production. Assembling these parts by
hand works for three of them; past twenty, the order of their building,
the choice of each implementation and what they share become the
program’s work. weft/inject does it at compile time: each part
declares what it needs, #Application checks the graph and writes the
code that builds it. There is no container looked up at run time, and no
reflection: a part nothing gives, or a cycle, is a compile error.
wv add weft/injectwv add weft/configThe program
Section titled “The program”A small notebook: a service, Notes, takes notes into a store, in memory
or in a file, and says what it does through a log.
import weaver.io.printimport weaver.task.{Shared}import weaver.test.{assert, assertEq}import weaver.{Fs}import weft.config.{Config, ConfigValue, ConfigError}import weft.inject.{Application, Injectable, Injector, InjectError}
/// Where the notes are kept.contract Store { fn all(self): String[]
fn add(self, note: String)}
/// Where the parts say what they do.contract Logger { fn line(self, text: String)}
@injectable(Logger)type Printer = { prefix: String @config("log.prefix", default) }
impl Logger for Printer { fn line(self, text: String) { print(self.prefix + text) }}
/// Notes in memory: one object, which all its holders share.@injectable(Store, name: "memory")sync type MemoryStore = { notes: Shared<String[]>, log: any Logger }
impl MemoryStore { @inject fn open(log: any Logger): MemoryStore = MemoryStore{notes: Shared.new([]), log}}
impl Store for MemoryStore { fn all(self): String[] = self.notes.get()
fn add(self, note: String) { self.log.line("memory: " + note) self.notes.write(xs => xs.push(note.copy())) }}
/// Notes in a file, one per line.@injectable(Store, name: "file")sync type FileStore = { path: String @config("store.path") log: any Logger}
impl Store for FileStore { fn all(self): String[] { val text = Fs.readText(self.path) catch _ => "" return text.split("\n").filter(l => !l.isEmpty()).map(l => l.copy()) }
fn add(self, note: String) { self.log.line("file ${self.path}: " + note) val text = Fs.readText(self.path) catch _ => "" val _ = Fs.writeText(self.path, text + note + "\n") }}
/// The service: takes notes, up to a limit.@injectabletype Notes = { store: any Store log: any Logger limit: Int @config("notes.limit", default)}
impl Notes { fn take(self, note: String) { if self.limit > 0 && self.store.all().len() >= self.limit { self.log.line("full, dropped: " + note) return } self.store.add(note) }}
#Applicationtype App = { notes: Notes, store: any Store }
fn main(args: String[]) ! ConfigError | InjectError { val config = Config.load<ConfigValue>(name: "notes", args: args)! val app = Injector<App>.build(config)! app.root.notes.take("buy milk") app.root.notes.take("call Ada") print("${app.root.store.all()}")}
fn appWith(settings: String[]): App ! ConfigError | InjectError { var args: String[] = [] for s in settings { args.push("--set"); args.push(s.copy()) } val config = Config.load<ConfigValue>(name: "notes", args: args, env: [], dirs: String[]())! return Injector<App>.build(config)!.root}
@test("one store, shared by the service and the root")fn shared() ! ConfigError | InjectError { val app = appWith(["inject.Store=memory", "notes.limit=1"])! app.notes.take("a") app.notes.take("b") assertEq(app.store.all(), ["a"])}
@test("the configuration chooses the file store")fn chosen() ! ConfigError | InjectError { val path = "notes-test.txt" val app = appWith(["inject.Store=file", "store.path=${path}", "log.prefix=> "])! app.notes.take("a") assertEq(app.store.all(), ["a"]) val _ = Fs.remove(path)}
@test("without a choice, the program does not start")fn unchosen() { assert(appWith([]) is Err(_), "no store chosen")}@injectable(Store, name: "memory")puts a type in the program’s registry, as an implementation of the contractStore, under a name. Without a contract, asNotes, the type is registered as itself.- A record is built from its fields, each injected: an
any Storeor an injectable type receives the implementation the registry chooses; a field tagged@config("key")receives the value at that key of the configuration, read into the field’s type.defaultgives the type’s default value,0or"", when the key is absent. - A type whose fields the injector cannot fill, as
MemoryStoreand itsSharedlist, gives a static function annotated@inject, whose parameters are injected as fields are. #Applicationon the root type gathers every injectable of the program, its modules and the packages it imports, checks the graph from the root, and writesInjector<App>.build, which builds it from a configuration.
Choosing an implementation
Section titled “Choosing an implementation”For a field of a contract, the injector takes, in this order:
- the implementation that
@named("memory"), written after the field, names; - the contract’s only implementation, if it has one, as
Loggerhere; - the configuration’s choice, at the key
inject.Store, or for one field alone,inject.Notes.store; - otherwise, nothing: a compile error.
The first two are settled at compile time. The third is read when the
program starts: the generated code holds the construction of each
candidate, and a match on the configured name picks one. Run without a
choice, the program stops before doing anything:
$ ./notesnotes: inject.Store: several implementations, none chosen: "file", "memory"$ ./notes --set inject.Store=memorymemory: buy milkmemory: call Ada["buy milk", "call Ada"]$ ./notes --set inject.Store=file --set store.path=notes.txt --set notes.limit=1file notes.txt: buy milkfull, dropped: call Ada["buy milk"]$ ./notes --set inject.Store=disknotes: inject.Store: "disk" is none of "file", "memory"$ ./notes --set inject.Store=filenotes: store.path: missingThe choice is a key of the configuration like any other: it comes from a
file, inject.Store = "file" in notes.toml, from the environment,
NOTES_INJECT__STORE=file, or from the command line. A key that only the
file store needs, store.path, is required only when that store is
chosen.
Scopes
Section titled “Scopes”App.store and Notes.store above are the same object: adding through
one, then listing through the other, shows the same notes. That is what
the first test checks. How many values the injector makes is the type’s
scope:
| Scope | One value per | Released |
|---|---|---|
.singleton |
program, shared by all its holders | with the injector |
.prototype |
injection, a new value each time | by whoever received it |
.request |
request, opened by app.scope(.request, …) |
when the request ends |
.task |
task, opened by app.scope(.task, …) |
when the task ends |
.thread |
thread of the pool | when the pool stops |
A singleton is shared, so only a type whose copies designate one object
can be one: a sync type, whose state lives in Shared, a Mutex or an
atomic, or an actor. Such a type is a singleton by default; a record of
values, which each holder would copy, is built at each injection. A value
declared .singleton is a compile error:
main.wft:84:1: `#Application` on App: Printer is a value, which each holder would copy: a singleton is one object, a `sync type` or an actorA value of a shorter scope is not held directly by one of a longer: a
singleton holds a Provider<Trail>, whose get() gives the current
request’s. @init marks a method called once the value is built:
import weaver.io.printimport weaver.task.{Shared}import weft.config.{Config, ConfigValue, ConfigError}import weft.inject.{Application, Injector, InjectError, Provider, injectable}
/// Counts the requests: a singleton, one object for the whole program.@injectablesync type Stats = { served: Shared<Int> }
impl Stats { @inject fn open(): Stats = Stats{served: Shared.new(0)}
@init fn start(self) { print("stats ready") }
fn count(self): Int = self.served.update(n => n + 1)}
/// What one request did: one object per request.@injectable(scope: .request)sync type Trail = { lines: Shared<String[]> }
impl Trail { @inject fn open(): Trail = Trail{lines: Shared.new([])}
fn note(self, line: String): Int = self.lines.write(xs => { xs.push(line.copy()) return xs.len() })}
#Applicationtype App = { stats: Stats, trail: Provider<Trail> }
fn handle(app: App, path: String): String ! InjectError { val _ = app.trail.get()!.note("GET " + path) val n = app.trail.get()!.note("200") return "request ${app.stats.count()}: ${n} lines in its trail"}
fn main() ! ConfigError | InjectError { val app = Injector<App>.build(Config.load<ConfigValue>(name: "scopes")!)! for path in ["/", "/about"] { print(app.scope(.request, () => handle(app.root, path))!) } if app.root.trail.get() is Err(e) { print(e.message()) }}stats readyrequest 1: 2 lines in its trailrequest 2: 2 lines in its trailTrail is of the request scope, and none is open: app.scope(.request, …)A type of the request, task or thread scope is annotated with
injectable, the meta function that weft.inject exports, in lowercase:
it also writes the Scoped contract the scope keeps its values by. The
values of a scope are released when it ends, in the reverse order of
their building.
With weft/rest, a request’s scope is a middleware of one line:
val scoped = Middleware.of((r, body, next) => app.scope(.request, () => next.run(r, &body)))Factories, lists and libraries
Section titled “Factories, lists and libraries”-
A factory.
@injectableon a function registers its result; its parameters are injected as fields are. This is how a library offers a value that is not a record of injected fields:@injectable(Clock, scope: .singleton)pub fn systemClock(@config("clock.zone") zone: String): SystemClock = SystemClock.at(zone)A factory of a singleton returns its type, not
any Clock, whose copies might not share. -
Every implementation. A field
(any Check)[]receives every implementation ofCheck, in the order of their names: health checks, routers, plugins. -
A library’s parts. An injectable in a package counts once a module of the program imports that package’s module: a library offers its parts by being imported, as it offers its types.
When the graph is wrong
Section titled “When the graph is wrong”Every mistake in the graph is found at compile time, with the chain that leads to it. Without its two stores, the notebook does not compile:
main.wft:81:1: `#Application` on App: App.store needs any Store, which no injectable givesThe other errors read the same way:
- a name no implementation has: App.store needs any Store named “disk”, which no injectable is;
- a cycle: a cycle: Hen, which needs Egg, which needs Hen;
- a request’s value held by the root: App (the root), which holds Trail
(request): a value outlives its scope; hold a
Provider<Trail>, which gives the current scope’s.
What can only go wrong when the program starts is an InjectError: a
choice unknown or missing, a configuration key missing, an @inject
function or an @init method that fails.
wv expand shows the code #Application writes: the constructions in
order, the match of each configured choice, the scopes.
Going further
Section titled “Going further”- Tests build the graph from a configuration of their own,
Config.load<ConfigValue>(…, env: [], dirs: String[]()), asappWithdoes above: the same program, with the memory store, without touching the machine. - There is no injection into a function’s parameters at a call, by setter, or through proxies: a value is the record it is. Nothing is registered at run time; the registry is the program’s, known when it compiles.