mjdi docsv0.10.0latest
Patterns and Best Practices
Practical guidance for structuring real applications with mjdi on Mojo
Source: mjdi/docs/patterns.md
Practical guidance for structuring real applications with mjdi on Mojo
1.2.0 — the shapes that work well under value semantics, and the traps.
Every pattern here is exercised somewhere in examples/ or tests/;
links point at the executable proof.
The composition root
Keep one place in the program where the registry is assembled and the
container is constructed — conventionally the top of main().
Everything below the root receives values, never the container.
def main() raises:
comptime app_registry = (
Registry()
.register_value[StoreConfig]()
.register_factory[IdGenerator, make_id_generator]()
.register[Inventory, provider_scope.singleton]()
.register[CheckoutService, provider_scope.scoped]()
)
var app = Container[type_of(app_registry)]()
app.set_value[StoreConfig](StoreConfig("usd", 80))
# ...resolve roots and run the application...
Why it matters: the root is the only code that knows the wiring, so every
other module stays container-free and constructible in isolation; the
compile-time validation has exactly one site to check; and the application
graph is legible in one screenful. Example 10
(examples/mixed_providers_app/app.mojo) is the reference
implementation.
Composing registries
Registries are immutable values, and every intermediate registry stays valid — so compose base and feature registries freely:
comptime core_registry = (
Registry()
.register[Logger, provider_scope.singleton]()
.register_value[AppConfig]()
)
comptime app_registry = (
core_registry
.register[UserRepository]()
.register[UserService]()
)
app_registry contains everything core_registry had, and core_registry
itself remains usable (tests love that: build the minimal registry the test
needs). There is no merge operator and none is needed — chaining from an
existing registry is composition. Because validation runs per
container construction, each composed variant gets its own full check.
Configuration via value providers
Configuration that comes from outside the graph (command line, environment,
a file your main() parsed) should enter the graph as value providers:
app.set_value[StoreConfig](StoreConfig("usd", 80))
Rules that make this robust:
- mjdi loads nothing; it carries values. Parsing stays in
main()— a deliberate framework boundary (Core concepts). - Transient services snapshot configuration at construction; singletons snapshot once per container. When you need fresh configuration, resolve a transient — or build a new container/scope.
- Scopes inherit copies of configured values at
create_scope()time and can override per scope withscope.set_value— useful for per-request configuration deltas.
Sharing mutable state
Under value semantics, "singleton with mutable fields" does not share anything (consumers get copies). The working pattern:
- Model the shared state as a value (or a handle to application-owned storage — a pool, a cache client).
- Register it as a value provider; every consumer receives a copy of the handle, which still points at the same underlying resource.
- Keep the services themselves transient or singleton as construction economics dictate — sharing comes from the handle, not the lifetime.
Worked example: Ownership and memory → Sharing observable state. The singletons that are worth registering are expensive constructions you want built once (the handle-holder itself, a formatter chain, a parser table).
Ports and adapters under value semantics
Without subtyping, "program against an interface" becomes composition: the abstraction is a plain struct whose dependency is the implementation.
struct UserRepository(Injectable):
var impl: Inject[SqlUserRepository]
def find_by_id(self, user_id: Int) -> String:
return self.impl.value().find_by_id(user_id)
Swap implementations by registering a different provider for
SqlUserRepository (or for a second type the abstraction can hold). Use
register_alias only when what you want is lifetime binding of a
concrete type — it constructs the requested type, not the target's
(Providers → Aliases). For test doubles:
declare the fake as its own type and compose it the same way — the
abstraction does not care what fills the field.
Own the mutation edge
Inject references are immutable views; mutating methods need owned
receivers (Dependency declaration).
Structure for it:
- Services expose read operations through injected dependencies
(
find_by_id,render,record). - Mutation happens where the instance is owned:
main(), or the code that constructed the value. - A service that must transform state resolves the dependency into an
owned local (via its
createoverride or a resolution at the root), mutates the local, and returns it.
This is not an inconvenience to route around — it is the ownership model telling you where mutation belongs: at the edge that owns the value.
Units of work with scopes
Request/transaction/session state: register the unit-of-work service
scoped, open a scope where the unit begins, and close it when it ends:
var scope = app.create_scope() # unit begins
var session = scope.resolve[Session]()
# ... run the unit ...
scope.close_scope() # unit ends; cached instances released
- Scoped services get their own canonical instance per scope — two concurrent units never see each other's state (each holds copies).
- Value overrides per unit:
scope.set_value[T]changes that scope only. - The full rules (what
close_scopereleases, what survives) are in Scopes and lifetimes; the executable demonstration isexamples/scoped_sessions/app.mojo.
Testing shapes
The patterns translate directly to tests — one comptime registry per
scenario, values set explicitly, golden strings for end-to-end output, and
value-provider snapshotting to observe construction counts. The complete
idiom list is in Testing.
Anti-patterns
Passing the container around (service locator). resolve[T]()
scattered through the codebase hides the graph from validation's consumer
tracking and makes every function container-dependent. Resolve at the root;
inject values.
Singleton for shared mutable fields. Silent divergence: each consumer mutates its own copy. Share via a value-provider handle instead (Sharing mutable state).
Capturing mutable state in factories. Factories are compile-time registered and may run in any container/scope built from the registry; a captured counter would be a bug factory. Factories compute, they do not remember.
Declaring Inject fields you never read to "document" intent. The
graph is built from declared fields — declared-but-unregistered
dependencies fail compilation even if your create override ignores them.
Declare what you resolve; resolve what you declare.
Resolving inside constructors of application objects (outside the
Injectable contract). Only provider-owned code (create) sees a
resolver; everywhere else, construct-then-wire ordering belongs to mjdi.
Direct construction leaves markers unresolved — and reading them aborts
with the diagnostic that says exactly what happened.
Reaching for string keys or dynamic lookups. mjdi has none by design;
if you feel the need, the type system wants a struct — small, named,
Copyable — as the key (Core concepts).