mjdi docsv0.10.0latest
Tutorial: Building a Task-Tracking Application
This tutorial builds a small but complete application — a task tracker — in
Source: mjdi/docs/tutorial.md
This tutorial builds a small but complete application — a task tracker — in
six steps, introducing one mjdi capability at a time: transient class
providers, value providers, factory providers, singletons, scoped sessions,
and the full registry assembly. Every code block and every output shown here
was compiled and run against mojo 1.2.0 (2016d0cd); you can reproduce
everything with mojo run -I . tutorial.mojo.
By the end you will have used every provider kind, every lifetime, and the compile-time safety net. The finished application is ~140 lines.
Step 0: Project setup
Create a directory with the mjdi package in it and an empty tutorial.mojo:
task-tracker/
├── mjdi/ <- the mjdi package
└── tutorial.mojo
All commands below run from task-tracker/. Every complete-code step
replaces the previous content of tutorial.mojo, so you can always run the
latest state:
mojo run -I . tutorial.mojo
The import line used by every step:
from mjdi import Container, Injectable, Inject, Registry
Later steps add from mjdi.provider import provider_scope.
Step 1: Your first services (class providers, transient)
Start with two services. Clock has no dependencies; TaskStore counts how
many tasks this instance stored, which will make lifetime behavior
visible.
from mjdi import Container, Injectable, Registry
struct Clock(Injectable):
"""Tells the time (the innermost service)."""
def now(self) -> String:
return String("10:05")
struct TaskStore(Injectable):
"""Transient service; counts how many tasks THIS instance stored."""
var count: Int
def __init__(out self):
self.count = 0
def add(mut self, title: String) -> String:
self.count += 1
return String("t#") + String(self.count) + String(" ") + title
def main() raises:
comptime app_registry = (
Registry()
.register[Clock]()
.register[TaskStore]()
)
var app = Container[type_of(app_registry)]()
var store_a = app.resolve[TaskStore]()
print(store_a.add("review PR")) # t#1 review PR
print(store_a.add("merge PR")) # t#2 merge PR <- same instance
var store_b = app.resolve[TaskStore]()
print(store_b.add("ship release")) # t#1 ship release <- fresh instance
Output:
t#1 review PR
t#2 merge PR
t#1 ship release
Two lessons live in this step:
- The default lifetime is transient. Each
resolve[TaskStore]()built a fresh instance — that is whystore_bcounts from one again. - Resolved values are owned. Calling the mutating method
addworks becausestore_ais an owned localvar. (A rule you will meet again: mutating methods needmut selfand an owned receiver.)
Step 2: Configuration (value providers)
Real services need configuration that the application supplies at runtime.
A value provider records the type at compile time; the value itself is
supplied per container with set_value:
from mjdi import Container, Injectable, Inject, Registry
struct Settings(Copyable):
"""Application configuration, supplied at runtime (value provider)."""
var prefix: String
def __init__(out self, var prefix: String):
self.prefix = prefix^
def __init__(out self, *, copy: Self):
self.prefix = copy.prefix
def main() raises:
comptime app_registry = Registry().register_value[Settings]()
var app = Container[type_of(app_registry)]()
app.set_value[Settings](Settings("tasks "))
print(app.has_value[Settings]()) # True
print(app.resolve[Settings]().prefix) # tasks
Output:
True
tasks
Rules to remember (all enforced where noted):
Settingsmust beCopyable— consumers receive copies of the stored value (compile-time check).- Resolving before
set_valueraises a runtime error naming the missing value;set_valueon a type that is not a value provider is a compile-time error. See Providers.
Step 3: Construction owned by a function (factory providers)
When construction should not go through the Injectable contract at all —
parsing configuration, picking an implementation, computing an initial
state — register a factory: a plain function the registry stores at
compile time and invokes at runtime.
struct TaskId(Copyable):
"""An identifier issued by a factory function."""
var value: String
def __init__(out self):
self.value = String("task-0007")
def __init__(out self, *, copy: Self):
self.value = copy.value
def make_task_id() raises -> TaskId:
"""The registered factory: a plain function with no captures."""
var id = TaskId()
return id^
Registration names the function as a parameter:
comptime app_registry = (
Registry()
.register_factory[TaskId, make_task_id]()
)
and resolution calls it fresh every time:
print(app.resolve[TaskId]().value) # task-0007
Factories are always transient — one invocation per resolution — and
must not capture mutable state. A factory that raises propagates its error
to the resolver. Details and rationale:
Providers.
Step 4: One construction per container (singleton)
A singleton class provider constructs once per container and hands out
copies of the canonical instance. To make the caching observable, let
AuditLog snapshot its configuration at construction time:
from mjdi.provider import provider_scope
struct AuditLog(Injectable, Copyable):
"""Singleton-lifetime service; snapshots its dependency at construction."""
var settings: Inject[Settings]
def __init__(out self):
self.settings = Inject[Settings]()
def __init__(out self, *, copy: Self):
self.settings = copy.settings.cloned()
def record(self, event: String) -> String:
return self.settings.value().prefix + String("logged: ") + event
comptime app_registry = (
Registry()
.register_value[Settings]()
.register[AuditLog, provider_scope.singleton]()
)
def main() raises:
var app = Container[type_of(app_registry)]()
app.set_value[Settings](Settings("tasks "))
print(app.resolve[AuditLog]().record("startup")) # tasks logged: startup
app.set_value[Settings](Settings("ops "))
print(app.resolve[AuditLog]().record("later")) # tasks logged: later
Output:
tasks logged: startup
tasks logged: later
The second line still says tasks because the canonical AuditLog was
constructed exactly once, before set_value changed the value — its
Inject[Settings] field holds a copy taken at construction time. Two
takeaways:
- Singletons snapshot their dependencies when they are constructed.
- If you change a value provider and want the new value, you need a transient resolution — or a new container/scope.
Note the Copyable conformance and the copy constructor
(__init__(out self, *, copy: Self)) with copy.settings.cloned(): cached
lifetimes hand out copies, so both the service and its Inject fields must
be copyable. This is covered in depth in
Ownership and memory.
Step 5: Units of work (scoped providers and Scope values)
A scoped provider caches one canonical instance per Scope — the mjdi
answer to "one instance per request / transaction / session". Scoped
services cannot be resolved from the container directly (that is a
compile-time-checked rule enforced with a runtime raise); they must go
through app.create_scope():
struct Session(Injectable, Copyable):
"""Scoped unit of work: one canonical construction per scope."""
var log: Inject[AuditLog]
var user: String
def __init__(out self):
self.log = Inject[AuditLog]()
self.user = String("anonymous")
def __init__(out self, *, copy: Self):
self.log = copy.log.cloned()
self.user = copy.user
def begin(mut self, name: String) -> String:
self.user = name
return self.log.value().record(String("began ") + name)
# ...in main, after the container is built:
var scope = app.create_scope()
var session = scope.resolve[Session]() # scoped: needs the scope
print(session.begin("alice")) # ops logged: began alice
var second = scope.resolve[Session]() # copy of the canonical session
print(second.begin("bob")) # ops logged: began bob
scope.close_scope() # release cached instances
Output (with the Step 4 registry extended by
.register[Session, provider_scope.scoped](), and the value already set to
"ops "):
ops logged: began alice
ops logged: began bob
second.begin("bob") works on a fresh copy of the canonical scoped
session — its user field is anonymous again, which is why the message
reads cleanly. Mutations never leak between consumers; that is value
semantics working for you, not against you.
create_scope() also copies the container's configured values into the
scope, so value-provided dependencies resolve identically inside it; later
set_value calls on the container do not affect existing scopes. The full
lifetime rules are in Scopes and lifetimes.
Step 6: Assemble the whole application
Now put every provider kind into one registry and add a top-level service that depends on the parts:
struct TaskService(Injectable):
"""The application service wired to every provider kind."""
var clock: Inject[Clock]
var settings: Inject[Settings]
var task_id: Inject[TaskId]
def add_task(self, title: String) -> String:
return (
self.task_id.value().value
+ String(" [")
+ self.clock.value().now()
+ String("] ")
+ self.settings.value().prefix
+ title
)
The complete registry — this is the composition root of the application —
assembled with every step so far into the final program. This is the whole
file: imports, all six structs, the factory, the registry, and main(). You
can paste it into tutorial.mojo wholesale and run it:
from mjdi import Container, Injectable, Inject, Registry
from mjdi.provider import provider_scope
struct Settings(Copyable):
"""Application configuration, supplied at runtime (value provider)."""
var prefix: String
def __init__(out self, var prefix: String):
self.prefix = prefix^
def __init__(out self, *, copy: Self):
self.prefix = copy.prefix
struct Clock(Injectable):
"""Tells the time (the innermost service)."""
def now(self) -> String:
return String("10:05")
struct TaskStore(Injectable):
"""Transient service; counts how many tasks THIS instance stored."""
var count: Int
def __init__(out self):
self.count = 0
def add(mut self, title: String) -> String:
self.count += 1
return String("t#") + String(self.count) + String(" ") + title
struct TaskId(Copyable):
"""An identifier issued by a factory function."""
var value: String
def __init__(out self):
self.value = String("task-0007")
def __init__(out self, *, copy: Self):
self.value = copy.value
def make_task_id() raises -> TaskId:
"""The registered factory: a plain function with no captures."""
var id = TaskId()
return id^
struct AuditLog(Injectable, Copyable):
"""Singleton-lifetime service; snapshots its dependency at construction."""
var settings: Inject[Settings]
def __init__(out self):
self.settings = Inject[Settings]()
def __init__(out self, *, copy: Self):
self.settings = copy.settings.cloned()
def record(self, event: String) -> String:
return self.settings.value().prefix + String("logged: ") + event
struct Session(Injectable, Copyable):
"""Scoped unit of work: one canonical construction per scope."""
var log: Inject[AuditLog]
var user: String
def __init__(out self):
self.log = Inject[AuditLog]()
self.user = String("anonymous")
def __init__(out self, *, copy: Self):
self.log = copy.log.cloned()
self.user = copy.user
def begin(mut self, name: String) -> String:
self.user = name
return self.log.value().record(String("began ") + name)
struct TaskService(Injectable):
"""The application service wired to every provider kind."""
var clock: Inject[Clock]
var settings: Inject[Settings]
var task_id: Inject[TaskId]
def add_task(self, title: String) -> String:
return (
self.task_id.value().value
+ String(" [")
+ self.clock.value().now()
+ String("] ")
+ self.settings.value().prefix
+ title
)
comptime app_registry = (
Registry()
.register_value[Settings]() # value
.register_factory[TaskId, make_task_id]() # factory
.register[Clock]() # class, transient
.register[TaskStore]() # class, transient
.register[TaskService]() # class, transient
.register[AuditLog, provider_scope.singleton]() # class, singleton
.register[Session, provider_scope.scoped]() # class, scoped
)
def main() raises:
var app = Container[type_of(app_registry)]()
app.set_value[Settings](Settings("tasks "))
var service = app.resolve[TaskService]()
print(service.add_task("write docs"))
print(app.resolve[AuditLog]().record("startup"))
var store_a = app.resolve[TaskStore]()
print(store_a.add("review PR"))
print(store_a.add("merge PR"))
var store_b = app.resolve[TaskStore]()
print(store_b.add("ship release"))
print(app.resolve[TaskId]().value)
app.set_value[Settings](Settings("ops "))
print(app.resolve[AuditLog]().record("later"))
var scope = app.create_scope()
var session = scope.resolve[Session]()
print(session.begin("alice"))
var second = scope.resolve[Session]()
print(second.begin("bob"))
scope.close_scope()
Complete output of the finished application (verified line by line):
task-0007 [10:05] tasks write docs
tasks logged: startup
t#1 review PR
t#2 merge PR
t#1 ship release
task-0007
tasks logged: later
ops logged: began alice
ops logged: began bob
Trace a few lines against the rules you learned — t#1 twice (transient),
tasks twice (singleton snapshot), ops in the scope lines (the scope's
AuditLog was constructed after the new value was set, because singletons
resolved through a scope cache in that scope) — and you have internalized
the lifetime model.
Step 7: The safety net
Break the application on purpose: delete the .register[Clock]() line and
recompile. The build fails before anything runs:
error: ... constraint failed: mjdi: no provider is registered for dependency
'Clock' required by 'TaskService'. Register it with
Registry().register[Clock]() (or a value/factory/alias provider) before
creating a Container.
Restore it, then try .register[AuditLog, provider_scope.singleton]()
twice (duplicate registration) or make the singleton AuditLog depend on a
scoped Session (lifetime conflict) — each is a compile error with a
diagnostic naming the offending types. The complete catalog of guaranteed
rejections is in Compile-time validation, and
the exact messages in Diagnostics.
Where to go next
- Providers — every registration kind, including alias providers, which this tutorial skipped to keep the graph linear.
- Scopes and lifetimes — the exact caching rules you just observed.
- Patterns and best practices — composition roots, testing patterns, and the anti-patterns worth avoiding.
- Examples guide — ten small applications, one per capability, each with its own test.