mjdi

Search documentation

Search the mjdi v0.10.0 documentation

mjdi docsv0.10.0latest

Scopes and Lifetimes

Every provider hands out instances according to a scope: transient

Source: mjdi/docs/scopes-and-lifetimes.md

Every provider hands out instances according to a scope: transient (fresh every time), singleton (one canonical construction per container), or scoped (one canonical construction per Scope value). This page defines the exact semantics of each, the Scope API, and the lifetime rules you can rely on. The ownership story behind "copies" is in Ownership and memory.

from mjdi.provider import provider_scope

comptime app_registry = (
    Registry()
    .register[RequestParser]()                       # transient (default)
    .register[Logger, provider_scope.singleton]()
    .register[Session, provider_scope.scoped]()
)

Transient

A new instance on every resolution.

  • app.resolve[T]() constructs T through its provider every time — for a class provider, that means a full create run (constructor plus Inject field population); for a factory provider, one factory invocation.
  • Transient resolutions capture value-provider values at construction: if set_value is called between two resolutions, a transient consumer constructed after the call sees the new value. This makes construction timing observable — tests/test_scopes.mojo relies on exactly this.
  • Consumers own what they receive outright; no Copyable requirement applies to the provider.

Use transient for stateless or per-operation services. It is the default: .register[T]() is .register[T, provider_scope.transient]().

Singleton

One canonical construction per container; consumers receive copies.

  • The first resolution constructs the canonical instance and caches it in the container's registry chain; every later resolution returns a copy of it. This is why singleton providers require T: Copyable (compile-time check: "singleton class provider 'T' requires the provided type to conform to Copyable").
  • The canonical instance is constructed once, so transient-side effects (value-provider snapshots taken during construction) happen at that moment. The canonical instance lives until the container is destroyed.
  • T may override create; the override runs once, at canonical construction.
  • Singletons may depend on singletons and transients. A singleton must not depend on a scoped provider — that is a compile-time rejection ("invalid lifetime relationship: singleton provider ... depends on scoped provider ..."), because the scoped instance would outlive its scope.

The mental model adjustment for framework users: a mjdi singleton is a cached construction, not shared mutable state. Copies mean field mutations never propagate between consumers. To share observable state, put it behind an explicitly shared handle — a value provider holding that handle is the idiomatic route (see Patterns).

One documented deviation to be aware of (see Known limitations): singletons resolved through a Scope are cached in that scope, not in the parent container, because a scope owns its own registry-chain instance and cannot safely reference the parent's state. Transient and scoped behaviors are unaffected. The tutorial observes this directly.

Scoped

One canonical construction per Scope value; consumers receive copies.

Scoped providers exist for units of work — a request, a transaction, a checkout session — that need their own instances without building a new container. T must be Copyable, exactly like singletons.

The non-negotiable rule: scoped providers cannot be resolved from the container. Violating it raises at the point of resolution:

mjdi: 'Session' is registered with the scoped lifetime and can only be
resolved through a Scope (obtain one with container.create_scope()), not
directly from the container.

(The provider's lifetime is a compile-time fact, so the specialization for "scoped provider, container context" is selected at compile time — and that specialization enforces the rule with a runtime raise. See tests/crash_expected/crash_scoped_from_container.mojo.)

The Scope API

var scope = app.create_scope()
var session = scope.resolve[Session]()
scope.set_value[StoreConfig](StoreConfig("usd", 90))   # override for this scope
scope.close_scope()                                    # release cached instances
MemberSemantics
resolve[T]()Resolves any registered type in this scope's context. Scoped providers cache here; singletons and transients resolved through the scope are cached/created in the scope (see the deviation note above).
set_value[T](/docs/0.10.0/v)Sets the value in this scope's slot, overriding the mirrored container value for this scope only.
close_scope()Releases every instance cached in this scope (scoped instances, plus anything cached here via resolution). Cached instances whose type conforms to InjectableLifecycle receive pre_destruct immediately before the release (while still fully usable). Value slots survive — they are configuration, not lifecycle state.

Releasing cached instances is what makes close_scope() the scoped lifecycle's deterministic end: after the call, the next resolution re-constructs. Services that declare lifecycle hooks see that release — see Lifecycle hooks. The container has the matching container-level release, Container.close(), for its cached singletons.

A Scope is a value like any other: create it where the unit of work begins, pass it to the code that participates in that unit, and close it when the unit ends. A scope can resolve everything the container can (both implement the same DependencyResolver contract), which is what lets one service graph serve every context.

Scopes and values

Value-provider values flow from container to scope by copy, at create_scope() time:

app.set_value[StoreConfig](StoreConfig("usd", 80))
var scope_one = app.create_scope()       # mirrors a copy of the config value
app.set_value[StoreConfig](StoreConfig("eur", 90))
var scope_two = app.create_scope()       # mirrors the new value
# scope_one still resolves the old value; container set_value calls
# never reach existing scopes.

Inside a scope, resolution order for a value provider T:

  1. The scope's own slot, if scope.set_value[T] was called on it;
  2. otherwise the value mirrored from the container at creation time.

This rule makes scopes self-contained: a service graph resolved inside a scope behaves identically regardless of when the container last changed its values. tests/test_scopes.mojo and examples/scoped_sessions/app.mojo verify every branch of it, including that close_scope releases the cached scoped instance (after closing, a new resolve re-constructs — and if the scope then sets its own value, the new construction sees it).

Choosing lifetimes: a worked rule of thumb

ServiceLifetimeWhy
Stateless logic (validators, formatters, pipelines)transientCheap construction, zero sharing concerns.
Configuration snapshotsvalue provider (or singleton that snapshots one)Supplied per container; singletons snapshot at construction.
Expensive-to-construct shared handle (connection pool, cache client)singletonOne construction per container; share the handle, not the service.
Per-request/per-transaction statescopedOne canonical construction per unit of work; released (with pre_destruct for lifecycle conformers) at close_scope().
Fresh-by-construction objects (ids, builders)factory (transient semantics)Construction logic owned by a function.

Lifetime rules summary

From \ Totransientsingletonscoped
transient consumerallowedallowedallowed (must resolve inside a scope)
singleton consumerallowedallowedcompile-time rejection
scoped consumerallowedallowedallowed

The singleton→scoped rejection is the only cross-lifetime rule the compiler enforces, and it exists because the scoped instance's lifetime cannot contain the singleton's. The full validation story is in Compile-time validation.