mjdi docsv0.10.0latest
Core Concepts
This document defines the vocabulary mjdi uses and the mental model behind
Source: mjdi/docs/core-concepts.md
This document defines the vocabulary mjdi uses and the mental model behind it: what "compile-time-first" means, what the moving parts are, and how Mojo's value semantics shape the design. Code samples here are minimal; the Tutorial and Usage guide show complete programs.
What dependency injection buys you
Dependency injection (DI) is a simple discipline: instead of a service
constructing the things it needs, it declares what it needs, and
something else (the DI library) supplies those things. The payoff is that
wiring becomes data you can inspect and validate, services become
constructible in isolation (with test doubles supplied where the real
dependencies would go), and the application's structure is visible in one
place instead of being scattered through __init__ calls.
mjdi implements that discipline for Mojo — and nothing else. It is a DI library, not an application framework: no HTTP, no routing, no configuration file formats, no lifecycle beyond object construction and instance caching.
What "compile-time-first" means
mjdi's defining property is the split between what happens before your program runs and what happens while it runs:
| Phase | mjdi does | mjdi does not |
|---|---|---|
| Compile time | Store provider registrations in the registry's type; discover Inject fields through reflection; build the dependency graph; validate it (missing providers, duplicates, lifetime conflicts, alias validity); specialize all resolution dispatch per registry. | Store instances, execute factories or constructors, hold any runtime state. |
| Runtime | Construct services; execute factories; cache singleton/scoped instances in slots; supply value-provider values; hand out owned values and copies. | Discover provider metadata that was knowable at compile time; fall back to a dynamic registry. |
The practical consequence: an invalid graph fails to compile. Deleting a provider that someone depends on, registering the same type twice, or making a singleton depend on a scoped service are all compile errors — with diagnostics that name the consumer and the dependency. The small residue of conditions that genuinely depend on runtime values (a value provider whose value was never set, a factory that raises) is reported at runtime, by design; see Compile-time validation for the exact boundary.
The moving parts
Services
A service is a struct that participates in the graph. Services conform
to Injectable and declare dependencies as Inject[T] fields:
struct UserService(Injectable):
var repository: Inject[UserRepository]
var logger: Inject[Logger]
Reading a dependency is always self.field.value() — a method call, because
Mojo 1.2.0 has no @property. The contract and its rules are in
Injectable; the marker itself is documented in
Dependency declaration.
Providers
A provider is a registration that answers "how do we make a T?" for
some service type T. mjdi has four kinds, plus the use_* spelling for
third-party types:
| Kind | Registration | Supplies T by |
|---|---|---|
| Class | .register[T]() | Invoking T's Injectable construction contract (default-construct, then populate Inject fields). |
| Value | .register_value[T]() + container.set_value[T](/docs/0.10.0/v) | Copying an application-supplied value out of a runtime slot. |
| Factory | .register_factory[T, make_t]() | Invoking a compile-time-registered function at runtime — fresh per resolution by default, or cached (singleton/scoped) with an explicit scope. |
| Alias | .register_alias[From, To]() | Constructing From through its own contract, with the lifetime configuration of To's provider. |
| Third-party (use family) | .use_value[T]() / .use_provider[T, make_t]() | The register_value / register_factory machinery spelled for types you do not own and cannot conform to Injectable — see Third-party structures. |
Each provider also has a scope (the lifetime of what it hands out) — except value providers (application-supplied); factories default to transient and support cached scopes via an explicit scope parameter. See Providers for each kind in depth.
Scopes (lifetimes)
A provider's scope says how often a new instance is produced:
| Scope | Meaning |
|---|---|
transient | A fresh instance on every resolution (the default). |
singleton | One canonical construction per container; consumers receive copies. |
scoped | One canonical construction per Scope value; consumers receive copies. |
Registered with a parameter: .register[T, provider_scope.singleton]().
Under Mojo's value semantics "one canonical instance" means one cached
construction; every consumer gets a copy of it, which is why cached
lifetimes require T: Copyable. The full semantics — including what
create_scope() and close_scope() actually do — are in
Scopes and lifetimes, and the ownership model is
in Ownership and memory.
The registry (compile time)
The registry is an immutable, type-level linked list of providers.
Registry() is the empty registry; every register* call returns a new
registry whose type parameters encode the accumulated provider set:
comptime app_registry = (
Registry()
.register[UserRepository]()
.register[Logger, provider_scope.singleton]()
.register[UserService]()
)
Nothing is mutated, nothing is global, and intermediate registries remain valid (which is how you compose base registries with feature registries — see Patterns). Because the provider set lives in the type, all lookups and validation are specialized per registry at compile time.
The container (runtime)
Container[type_of(app_registry)]() builds the runtime half: one registry
chain instance that owns the value slots and singleton caches, specialized
resolution dispatch, and — in its constructor — the full graph validation
walk. The type_of spelling is required because the registry is a
compile-time value and a type parameter cannot bind a value directly
(one of the documented deviations in
Known limitations).
The container's public surface is deliberately small: resolve[T](),
set_value[T](/docs/0.10.0/v), has_value[T](), and create_scope(). See
API reference.
Scope values (runtime)
app.create_scope() returns a Scope[registry] value that resolves in its
own context: scoped providers cache per scope, and scope.close_scope()
releases what the scope cached. Scopes exist so a unit of work (a request,
a transaction, a checkout session) can have its own instances without
building a new container. See
Scopes and lifetimes.
The composition root
The composition root is the one place in your program where the registry
is assembled and the container is built — conventionally the top of
main(). Everything below it receives values, never the container.
Keeping the root small and singular is the most valuable habit when using
mjdi; see Patterns.
Value semantics is not a footnote
Mojo is a value-semantics language: an owned value has exactly one holder, and there is no safe way to hand out a second reference to it. mjdi takes this seriously instead of hiding it:
- Transient resolutions return a fresh instance the caller owns.
- Singleton and scoped providers cache one canonical construction and hand out copies. Sharing observable state means putting that state behind an explicitly shared handle (a value provider works well), not mutating a singleton's fields.
- Services whose cached lifetime requires copying must be
Copyableand implement the copy constructor; theirInjectfields clone themselves withcloned().
If you have used DI frameworks in reference-semantics languages, this is the single biggest adjustment — the Ownership and memory document is written for exactly that transition.
What mjdi is not
The product requirements draw a hard boundary, and the package honors it. mjdi does not provide:
- HTTP servers, routing, controllers, or middleware;
- application modules, plugin systems, or an event bus;
- configuration file formats or environment handling (value providers carry values, mjdi does not load them);
- ORM features or database tooling;
- a CLI, logging, or telemetry.
If you need those, build them on top of mjdi as ordinary Mojo libraries whose wiring happens at your composition root.
Concept map for the experienced
If you have used other DI libraries, the rough translation is:
| Elsewhere | mjdi |
|---|---|
| Module / component | comptime registry composition (Registry() chains) |
@Inject annotation / constructor injection | Inject[T] fields (field injection, two-phase construction) |
bind(Interface.class).to(Impl.class) | composition under value semantics (an Inject[Impl] field inside your abstraction), or register_alias for lifetime binding |
@Singleton | provider_scope.singleton |
| Request scope / child container | create_scope() / Scope[registry] |
get<T>() service locator | resolve[T]() — legitimate only at the composition root |
| Runtime graph validation | compile-time validation, with a documented runtime remainder |
The last row is the point of the library: the graph is a compile-time artifact, and the compiler is the validator.