Standard library · Language and runtime

dependency

Dependency injection in the spirit of google/wire: named providers, interface bindings, cleanups and a graph check for missing dependencies and cycles.

import dependency

dependency wires the layers of a program together: a repository, a service that uses it, a handler that uses the service. You register one provider per component, name what each one needs, and ask for the top of the graph. Each component is built once, and Close runs the cleanups in the reverse of the order they were built.

Salam has no runtime type information, so providers are identified by a name you choose, usually the type name. A provider is a function that takes the container and returns the component; it reads its own dependencies with Get. The second string of Provide lists those dependencies so that Build can check the whole graph before anything runs.

Providers and the graph check

Provide(c, name, needs, witness, factory) registers a provider. needs is a comma separated list of provider names, empty when there are none. witness is any value of the component's type; it only tells the compiler which type the factory returns. Build returns an empty string when the graph is sound and otherwise a message that names the problem: a missing dependency, a duplicate provider or a dependency cycle with the full path.

dependency-quickstart.salam
import dependency

struct Repo:
    pub rows: int = 0
end

struct Service:
    pub repo: Repo = Repo {}
    pub func Count(): int:
        ret this.repo.rows
    end
end

struct Handler:
    pub svc: Service = Service {}
    pub func Serve(): str:
        ret "rows=" + this.svc.Count()
    end
end

func main:
    c := dependency.New()
    dependency.Provide(c, "Repo", "", Repo {}, (_c: dependency.Container): ret Repo { rows = 3 } end)
    dependency.Provide(c, "Service", "Repo", Service {}, (cx: dependency.Container): mut r := Repo {} _ok := dependency.Get(cx, "Repo", r) ret Service { repo = r } end)
    dependency.Provide(c, "Handler", "Service", Handler {}, (cx: dependency.Container): mut s := Service {} _ok := dependency.Get(cx, "Service", s) ret Handler { svc = s } end)
    err := dependency.Build(c)
    if err != "":
        println err
        ret 1
    end
    mut h := Handler {}
    _ok := dependency.Get(c, "Handler", h)
    println h.Serve()
    dependency.Close(c)
end
Output
rows=3

Get(c, name, out) builds the component if it does not exist yet and copies it into out. It returns false and sets Error when the name is unknown or a cycle is hit at run time.

Interfaces, values and cleanups

Bind(c, "Store", "MemStore") makes the name Store resolve to the provider MemStore, which is how a service asks for an interface and gets the implementation chosen at the wiring site. Value registers a ready made value such as a configuration struct. OnClose attaches a cleanup to a provider; Close runs the cleanups of the components that were actually built, last built first, and frees the container.

Built lists the names in the order they were built and Count the number of registered names.

Reading the errors

Build only looks at the registered names and their needs lists, it never runs a factory. A sound graph gives an empty string; the other three messages are missing dependency: Service needs Repo, duplicate provider: Repo and dependency cycle: A -> B -> C -> A. Call it once at startup and stop there if the text is not empty. Get with a name nobody registered returns false and leaves missing provider: Nope in Error.

dependency-guide-errors.salam
import dependency

func report(label: str, c: dependency.Container):
    msg := dependency.Build(c)
    println label + ":", msg == "" ? "sound" : msg
    dependency.Close(c)
end

func main:
    ok := dependency.New()
    dependency.Provide(ok, "Repo", "", 0, (_c: dependency.Container): ret 1 end)
    report("fine", ok)

    missing := dependency.New()
    dependency.Provide(missing, "Service", "Repo", 0, (_c: dependency.Container): ret 1 end)
    report("missing", missing)

    twice := dependency.New()
    dependency.Provide(twice, "Repo", "", 0, (_c: dependency.Container): ret 1 end)
    dependency.Provide(twice, "Repo", "", 0, (_c: dependency.Container): ret 2 end)
    report("duplicate", twice)

    loop := dependency.New()
    dependency.Provide(loop, "A", "B", 0, (_c: dependency.Container): ret 1 end)
    dependency.Provide(loop, "B", "C", 0, (_c: dependency.Container): ret 2 end)
    dependency.Provide(loop, "C", "A", 0, (_c: dependency.Container): ret 3 end)
    report("cycle", loop)

    empty := dependency.New()
    mut n := 0
    println "get:", dependency.Get(empty, "Nope", n), dependency.Error(empty)
    dependency.Close(empty)
end
Output
fine: sound
missing: missing dependency: Service needs Repo
duplicate: duplicate provider: Repo
cycle: dependency cycle: A -> B -> C -> A
get: false missing provider: Nope

Choosing an implementation at the wiring site

Put the choice in one function that builds the container. Here Value stores the configuration, two providers make a Store in different ways, and Bind points the name Store at one of them depending on the environment. Code that asks for Store does not change. Only the components that something actually asked for are built: Built lists 1 name in the test container and 2 in the production one, out of 4 registered.

dependency-guide-swap.salam
import dependency

struct Config:
    pub env: str = ""
end

struct Store:
    pub kind: str = ""
end

func build(env: str): dependency.Container:
    c := dependency.New()
    dependency.Value(c, "Config", Config { env = env })
    dependency.Provide(c, "Mem", "", Store {}, (_c: dependency.Container): ret Store { kind = "memory" } end)
    dependency.Provide(c, "Disk", "Config", Store {}, (cx: dependency.Container): mut cfg := Config {} _ok := dependency.Get(cx, "Config", cfg) ret Store { kind = "disk for " + cfg.env } end)
    if env == "test":
        dependency.Bind(c, "Store", "Mem")
    else:
        dependency.Bind(c, "Store", "Disk")
    end
    ret c
end

func main:
    for_env := ["test", "prod"]
    each env in for_env:
        c := build(env)
        println env + ":", dependency.Build(c) == "" ? "sound" : "broken"
        mut s := Store {}
        _ok := dependency.Get(c, "Store", s)
        println "  store is", s.kind
        built := dependency.Built(c)
        println "  built", built.Len(), "of", dependency.Count(c)
        built.Free()
        dependency.Close(c)
    end
end
Output
test: sound
  store is memory
  built 1 of 4
prod: sound
  store is disk for prod
  built 2 of 4

Build once, close in reverse

Every provider is a singleton: asking twice for Cache runs its factory once and hands out copies of the same value. The cleanups registered with OnClose run from the last built component to the first, so the cache is closed before the database it holds. A second Close does nothing.

dependency-guide-lifecycle.salam
import dependency

mut made := 0

struct Db:
    pub id: int = 0
end

struct Cache:
    pub db: Db = Db {}
end

func main:
    c := dependency.New()
    dependency.Provide(c, "Db", "", Db {}, (_c: dependency.Container): made++ ret Db { id = 7 } end)
    dependency.Provide(c, "Cache", "Db", Cache {}, (cx: dependency.Container): mut d := Db {} _ok := dependency.Get(cx, "Db", d) ret Cache { db = d } end)
    dependency.OnClose(c, "Db", Db {}, (d: Db): println "closing db", d.id end)
    dependency.OnClose(c, "Cache", Cache {}, (k: Cache): println "closing cache over", k.db.id end)

    before := dependency.Built(c)
    println "before", before.Len()
    before.Free()
    mut a := Cache {}
    mut b := Cache {}
    _x := dependency.Get(c, "Cache", a)
    _y := dependency.Get(c, "Cache", b)
    println "factory runs", made
    built := dependency.Built(c)
    println "order", built.Get(0), built.Get(1)
    built.Free()
    dependency.Close(c)
    dependency.Close(c)
    println "done"
end
Output
before 0
factory runs 1
order Db Cache
closing cache over 7
closing db 7
done

Types

Container

#
struct Container

A dependency container: the registered providers and the components built so far. Copies of it share the same state.

NameTypeDescription
stState*The shared state of the container.

Functions

New

#
func New(): Container

Creates an empty container.

dependency-Provide.salam
import dependency

func main:
    c := dependency.New()
    dependency.Provide(c, "Base", "", 0, (_c: dependency.Container): ret 10 end)
    dependency.Provide(c, "Double", "Base", 0, (cx: dependency.Container): mut b := 0 _ok := dependency.Get(cx, "Base", b) ret b * 2 end)
    mut d := 0
    if dependency.Get(c, "Double", d):
        println d
    end
    dependency.Close(c)
end
Output
20

Provide

#
func Provide<T>(c: Container, name: str, needs: str, _witness: T, factory: func(Container): T)

Registers a provider under a name. needs is a comma separated list of provider names, the witness is any value of the component type and only fixes T, and factory builds the component.

The example for this item is shown with the ones above: dependency-Provide.salam

Value

#
func Value<T>(c: Container, name: str, v: T)

Registers a ready value, such as a configuration, under a name.

dependency-Value.salam
import dependency

struct Config:
    pub port: int = 0
end

func main:
    c := dependency.New()
    dependency.Value(c, "Config", Config { port = 8080 })
    mut cfg := Config {}
    if dependency.Get(c, "Config", cfg):
        println cfg.port
    end
    dependency.Close(c)
end
Output
8080

Bind

#
func Bind(c: Container, iface: str, concrete: str)

Makes the name iface resolve to the provider concrete.

dependency-Bind.salam
import dependency

interface Greeter:
    func Hello(): str
end

struct English:
    pub func Hello(): str:
        ret "hello"
    end
end

func main:
    c := dependency.New()
    dependency.Provide(c, "English", "", English {}, (_c: dependency.Container): ret English {} end)
    dependency.Bind(c, "Greeter", "English")
    mut g := English {}
    if dependency.Get(c, "Greeter", g):
        println g.Hello()
    end
    dependency.Close(c)
end
Output
hello

OnClose

#
func OnClose<T>(c: Container, name: str, _witness: T, f: func(T))

Attaches a cleanup to a provider. Close calls it if the component was built.

dependency-OnClose.salam
import dependency

struct Conn:
    pub id: int = 0
end

func main:
    c := dependency.New()
    dependency.Provide(c, "Conn", "", Conn {}, (_c: dependency.Container): ret Conn { id = 7 } end)
    dependency.OnClose(c, "Conn", Conn {}, (v: Conn): println "closing", v.id end)
    mut x := Conn {}
    _ok := dependency.Get(c, "Conn", x)
    dependency.Close(c)
end
Output
closing 7

Build

#
func Build(c: Container): str

Checks the graph without building anything. Returns an empty text when it is sound, otherwise a message that names the missing dependency, the duplicate provider or the cycle.

dependency-Build.salam
import dependency

func main:
    c := dependency.New()
    dependency.Provide(c, "Service", "Repo", 0, (_c: dependency.Container): ret 1 end)
    println dependency.Build(c)
    dependency.Provide(c, "Repo", "Service", 0, (_c: dependency.Container): ret 2 end)
    println dependency.Build(c)
    dependency.Close(c)
end
Output
missing dependency: Service needs Repo
dependency cycle: Service -> Repo -> Service

Get

#
func Get<T>(c: Container, name: str, out &: T): bool

Builds the component if it does not exist yet and copies it into out. Returns false and sets Error when the name is unknown or a cycle is reached.

The example for this item is shown with the ones above: dependency-Provide.salam

Error

#
func Error(c: Container): str

The last error of the container, empty when there is none.

Count

#
func Count(c: Container): int

The number of registered names.

Built

#
func Built(c: Container): Vector<str>

The names that have been built, in the order they were built.

Close

#
func Close(c: Container)

Runs the cleanups starting from the last component built, and frees the container. Safe to call twice.

The example for this item is shown with the ones above: dependency-OnClose.salam