mjdi

Search documentation

Search the mjdi v0.10.0 documentation

mjdi docsv0.10.0latest

API Reference

Complete reference for mjdi 0.8.0 on Mojo 1.2.0, organized by area (P1-12). Signatures are generated from the source (scripts/gen_api_reference.py parses mjdi/.mojo), so the documented signatures cannot drift from the declarations; regenerate with python3 scripts/gen_api_reference.py (CI re-checks with --check). Behavior summaries link to the deep-dive pages. Everything under Package exports imports from mjdi directly.

Source: mjdi/docs/api-reference.md

Complete reference for mjdi 0.8.0 on Mojo 1.2.0, organized by area (P1-12). Signatures are generated from the source (scripts/gen_api_reference.py parses mjdi/*.mojo), so the documented signatures cannot drift from the declarations; regenerate with python3 scripts/gen_api_reference.py (CI re-checks with --check). Behavior summaries link to the deep-dive pages. Everything under Package exports imports from mjdi directly.

Package exports

from mjdi import (
    Container,
    Scope,
    is_linear,
    mjdi_linear,
    validate_registry,
    DependencyResolver,
    explain_resolution,
    graph_dot,
    graph_json,
    registry_summary,
    ContainerGuard,
    ScopeGuard,
    with_container,
    with_scope,
    Inject,
    Injectable,
    resolve_dependencies,
    InjectableLifecycle,
    LinearProvider,
    LinearService,
    CacheStats,
    DebugLog,
    RuntimeValidation,
    TraceEvent,
    TraceLog,
    provider_kind,
    provider_origin,
    provider_scope,
    Registry,
    add_provider,
    Keyed,
    DefaultKey,
    All,
    OptionalInject,
    Assisted,
    ProviderDecorator,
    assert_missing_values,
    assert_resolve_fails_with,
    assert_stats_line,
    assert_trace_count,
    assert_trace_last,
    assert_validate_runtime,
    assert_value_inventory,
)

Testing helpers

Source: mjdi/testing.mojo — import from mjdi directly.

The assertion family for mjdi test suites (P1-08). Each helper is generic over the container/scope specialization it asserts on. See Testing for the full guide and examples/testing_patterns for runnable patterns.

from mjdi import (
    assert_missing_values,      # pins the missing-value report exactly
    assert_value_inventory,     # pins the value-provider inventory
    assert_validate_runtime,    # pins the startup-validation verdict
    assert_resolve_fails_with,  # expects a specific mjdi runtime diagnostic
    assert_trace_count,         # pins the lifecycle-trace event count
    assert_trace_last,          # pins the last recorded trace event
    assert_stats_line,          # pins cache-statistics fragments
)

Scope companions (assert_trace_count_scope, assert_trace_last_scope, assert_stats_line_scope) mirror the trace/stat assertions for scopes.

Advanced APIs

Source: mjdi/provider.mojo and mjdi/registry.mojo — importable as from mjdi.provider import ....

The library's internal vocabulary, exported for introspection and testing (the mixed-providers example uses ProviderQueryable bounds for its comptime report):

  • ProviderQueryable, ProviderChain, RuntimeChain — the chain contracts (comptime queries, provider dispatch, runtime slot access).
  • ProviderSpec, ProviderContext, ProviderValidator, GraphRenderer, graph_render — the descriptor, context, validation, and graph-rendering contracts.
  • ClassProvider, ValueProvider, FactoryProvider, AliasProvider — the provider descriptors.
  • TypeChain, EmptyChain, ChainLike — comptime type lists used by cycle detection.
  • The chain_* free-function dispatch helpers (chain_provides, chain_provide, chain_scope_of, chain_node_count, chain_service_index, ...) — the safe cross-node evaluation pattern every chain walk routes through.
  • provider_origin_label, provider_kind_label, provider_scope_label, graph_bool, graph_separator — the stable metadata labels the graph export and explain-resolution render.

Getting started

Registry

Source: mjdi/registry.mojo

The empty provider registry — the starting point of every composition. Registration methods return a new registry whose type encodes the accumulated provider set; nothing is mutated.

struct Registry(ProviderChain, RuntimeChain, Defaultable, Movable, Deinitable)

Graph validation runs when a Container is constructed. See Getting started and Providers.

Container

Source: mjdi/container.mojo

The runtime DI container specialized for the compile-time registry: type-based resolution, runtime value slots, scopes, runtime validation, tracing, statistics, and the re-entrancy guard.

struct Container[
    registry: ProviderChain & RuntimeChain & Defaultable & Movable & Deinitable,
    traced: Bool = False,
    collect_stats: Bool = False,
    reentrancy_guard: Bool = True,
    debug_tracking: Bool = False,
](ProviderContext, Defaultable)

Generic parameters: registry (the provider chain), traced (P1-15, default False), collect_stats (P1-16, default False), reentrancy_guard (P1-20, default True). See Container.

Inject

Source: mjdi/inject.mojo

The dependency marker: a struct field declared as var repo: Inject[Repo] marks a dependency mjdi resolves and populates automatically.

struct Inject[T: Movable & Deinitable, K: AnyType = DefaultKey](ResolvableField, Defaultable)

value() aborts when read before resolution (MJDI-A001). See Dependency declaration.

Injectable

Source: mjdi/injectable.mojo

The construction contract for automatically-wired types: default-construct, resolve every Inject field, run lifecycle hooks.

trait Injectable(Defaultable, Movable, Deinitable)

Override create for custom construction. See Injectable.

validate_registry

Source: mjdi/dependency_graph.mojo

Validates a registry's whole dependency graph at compile time (missing providers, cycles, lifetime conflicts).

def validate_registry[Q: AnyType]() -> None

Container construction runs this automatically; call it explicitly to trigger the same diagnostics earlier. See Compile-time validation.

Everyday APIs

with_scope

Source: mjdi/guards.mojo

The lexical scope guard (P1-13): runs a body with a freshly created scope and guarantees close_scope() on normal completion and on every error path.

def with_scope[
    registry: ProviderChain & RuntimeChain & Defaultable & Movable & Deinitable,
    R: Movable & Deinitable,
    traced: Bool = False,
    collect_stats: Bool = False,
    reentrancy_guard: Bool = True,
    debug_tracking: Bool = False,
](
    mut container: Container[registry, traced, collect_stats, reentrancy_guard, debug_tracking],
    body: def(mut Scope[registry, traced, collect_stats, reentrancy_guard, debug_tracking]) raises thin -> R,
) raises -> R

The body is a thin capture-free function taking the scope by mutable reference and returning a Movable result, which with_scope forwards. See Scope guard.

with_container

Source: mjdi/guards.mojo

The container guard (P1-14): runs a body with the container and guarantees close() on both exit paths.

def with_container[
    registry: ProviderChain & RuntimeChain & Defaultable & Movable & Deinitable,
    R: Movable & Deinitable,
    traced: Bool = False,
    collect_stats: Bool = False,
    reentrancy_guard: Bool = True,
    debug_tracking: Bool = False,
](
    mut container: Container[registry, traced, collect_stats, reentrancy_guard, debug_tracking],
    body: def(mut Container[registry, traced, collect_stats, reentrancy_guard, debug_tracking]) raises thin -> R,
) raises -> R

See Container guard.

RuntimeValidation

Source: mjdi/observability.mojo

The structured result of validate_runtime() (P1-07): a validity flag, a problem count, and a human-readable report.

struct RuntimeValidation(Defaultable, Copyable, Movable, Deinitable)

See Runtime validation.

Providers

provider_kind

Source: mjdi/provider.mojo

The provider category enum: class_provider, value_provider, factory_provider, alias_provider.

__enum provider_kind

Enums have no __eq__ on the target compiler — compare _get_enum_discriminant()s. See Providers.

provider_origin

Source: mjdi/provider.mojo

Records which registration method produced a descriptor (graph metadata; how override* registrations are recognized).

__enum provider_origin

See Graph export.

LinearProvider

Source: mjdi/linear.mojo

The linear provider descriptor: participates in the registry chain with the linear lifetime (constructed per use).

struct LinearProvider[T: LinearService](ProviderSpec)

See Linear services.

Lifetimes

provider_scope

Source: mjdi/provider.mojo

The lifetime enum: transient (fresh per resolution), singleton (one canonical instance per resolving context), scoped (one per Scope).

__enum provider_scope

Cached lifetimes hand out copies — the provided type must be Copyable. See Scopes and lifetimes.

Registry composition

ProviderRegistry

Source: mjdi/registry.mojo

One registered provider plus the rest of the registry — the chain node type every register*/override* call returns.

struct ProviderRegistry[
    H: ProviderSpec,
    Rest: ProviderChain & RuntimeChain & Defaultable & Movable & Deinitable,
](ProviderChain, RuntimeChain, Defaultable, Movable, Deinitable)

See Registry overrides for the override family.

Scope

Scope

Source: mjdi/container.mojo

A logical resolution scope owning its own instance caches: scoped providers cache per scope; singletons resolved through a scope cache in it.

struct Scope[
    registry: ProviderChain & RuntimeChain & Defaultable & Movable & Deinitable,
    traced: Bool = False,
    collect_stats: Bool = False,
    reentrancy_guard: Bool = True,
    debug_tracking: Bool = False,
](ProviderContext, Defaultable)

Mirrors the Container's runtime-validation and observability surface (value_inventory, missing_values, validate_runtime, tracing, statistics, and its own re-entrancy tracking). See Scopes and lifetimes and Scope guard.

Container

CacheStats

Source: mjdi/observability.mojo

Cache-statistics counters (P1-16): hits, misses, constructions, insertions, releases, factory runs, scope creations.

struct CacheStats(Defaultable, Copyable, Movable, Deinitable)

Per-owner (container or scope); read with stats_snapshot()/stats_report(); reset_stats() clears. See Cache statistics.

DebugLog

Source: mjdi/observability.mojo

The opt-in lifecycle-safety tracking log (P0-03): cache insertions and releases recorded by the debug_tracking=True specializations.

struct DebugLog[capacity: Int = 64](Defaultable, Movable, Deinitable)

Pull model like TraceLog (bounded, overflow-flagged); read through debug_report()/debug_count(). The MJDI-D001/D002 destructor diagnostics print rather than record (destructors cannot write into a surviving structure). See Lifecycle safety diagnostics.

Lifecycle

InjectableLifecycle

Source: mjdi/lifecycle.mojo

The opt-in lifecycle contract: post_construct runs after mjdi finishes wiring an instance; pre_destruct runs before mjdi releases a cached canonical instance.

trait InjectableLifecycle

Both methods are required (no trait defaults). See Lifecycle hooks.

TraceEvent

Source: mjdi/observability.mojo

One recorded lifecycle event (P1-15): kind, service, and detail strings in deterministic order.

struct TraceEvent(Defaultable, Copyable, Movable, Deinitable)

See Lifecycle tracing.

TraceLog

Source: mjdi/observability.mojo

The bounded, ordered trace-event log behind traced containers and scopes (TraceLog[capacity], default 256 events, overflow flag).

struct TraceLog[capacity: Int = 256](Defaultable, Movable, Deinitable)

See Lifecycle tracing.

Linear resources

LinearService

Source: mjdi/linear.mojo

The linear-service contract: construct in place through the resolver-taking constructor, consume through exactly one visitor, destroy explicitly.

trait LinearService(Defaultable)

Linear services opt out of Movable/Deinitable; the value-returning resolve cannot apply. See Linear services.

mjdi_linear

Source: mjdi/annotations.mojo

The canonical linear annotation value — a comptime LinearMarker whose label is the literal "mjdi:linear".

comptime mjdi_linear = LinearMarker()  # label: "mjdi:linear"

# Attach it above the struct definition:
#     @__annotation(mjdi_linear)
#     struct DbLease(LinearService):
#         ...

Attach with @__annotation(mjdi_linear) above the struct.

is_linear

Source: mjdi/annotations.mojo

The compile-time query: true when T carries the mjdi_linear annotation.

def is_linear[T: AnyType]() -> Bool

See Linear services.

ScopeGuard

Source: mjdi/guards.mojo

Ownership guard for scopes (P1-13): move a scope in, resolve through the guard, close exactly once (explicitly or in __deinit__, which fires during error unwinding too).

struct ScopeGuard[
    registry: ProviderChain & RuntimeChain & Defaultable & Movable & Deinitable,
    traced: Bool = False,
    collect_stats: Bool = False,
    reentrancy_guard: Bool = True,
    debug_tracking: Bool = False,
](Defaultable, Deinitable)

See Scope guard.

ContainerGuard

Source: mjdi/guards.mojo

Ownership guard for containers (P1-14): the container-level sibling of ScopeGuard with close() exactly once.

struct ContainerGuard[
    registry: ProviderChain & RuntimeChain & Defaultable & Movable & Deinitable,
    traced: Bool = False,
    collect_stats: Bool = False,
    reentrancy_guard: Bool = True,
    debug_tracking: Bool = False,
](Defaultable, Deinitable)

See Container guard.

Diagnostics

DependencyResolver

Source: mjdi/provider.mojo

The public resolution capability trait implemented by Container and Scope.

trait DependencyResolver

Custom construction overrides take R: DependencyResolver. See Injectable.

Tooling

graph_json

Source: mjdi/graph.mojo

Exports a registry's dependency graph as deterministic, versioned JSON (schema mjdi.graph/1) — nodes (service, provider kind, registration source, effective lifetime, alias/linear/copyable flags, validity) and edges (consumer → dependency).

def graph_json[Q: ProviderChain]() -> String

The export never validates: invalid graphs export with problems marked. See Graph export.

graph_dot

Source: mjdi/graph.mojo

Exports the same graph as Graphviz DOT with per-kind colors, dashed alias edges, hexagonal linear nodes, and red invalid borders.

def graph_dot[Q: ProviderChain]() -> String

See Graph export.

explain_resolution

Source: mjdi/graph.mojo

Explains how a service is resolved (P1-04): provider, effective lifetime, dependency chain, construction path, cache owner, scope requirement, copyability, validation status.

def explain_resolution[Q: ProviderChain, T: AnyType]() -> String

See Explain resolution.

registry_summary

Source: mjdi/graph.mojo

A one-line registry summary (providers: N) for reports.

def registry_summary[Q: ProviderChain]() -> String

See Graph export.

Advanced composition (P2)

register_keyed

Source: mjdi/registry.mojo

Registers a class provider under a compile-time key type (P2-01): multiple implementations of one abstraction coexist as (service, key) pairs encoded in the registry type.

    def register_keyed[
        T: Movable & Deinitable,
        K: AnyType,
        scope: provider_scope = provider_scope.transient,
    ](
        self,
    ) -> ProviderRegistry[KeyedClassProvider[T, K, scope], Self]

Duplicate pairs are rejected at registration (MJDI-E004 keyed variant); DefaultKey is reserved (MJDI-E023). Resolve through Inject[T, K] / Container.resolve[Keyed[T, K]](). See Keyed and qualified registrations.

register_keyed_value

Source: mjdi/registry.mojo

Registers a runtime value under a compile-time key: set_value[Keyed[T, K]](Keyed[T, K](/docs/0.10.0/v)) supplies it before resolution.

    def register_keyed_value[T: Movable & Deinitable, K: AnyType](
        self,
    ) -> ProviderRegistry[KeyedValueProvider[T, K], Self]

Same Copyable rules as register_value. See Keyed and qualified registrations.

register_keyed_factory

Source: mjdi/registry.mojo

Registers a factory under a compile-time key: register_keyed_factory[T, K, factory, scope]() — the factory runs like a register_factory provider.

    def register_keyed_factory[
        T: Movable & Deinitable,
        K: AnyType,
        factory: def() raises thin -> T,
        scope: provider_scope = provider_scope.transient,
    ](
        self,
    ) -> ProviderRegistry[KeyedFactoryProvider[T, K, factory, scope], Self]

Same lifetime rules as register_factory. See Keyed and qualified registrations.

Keyed

Source: mjdi/keyed.mojo

The keyed provider marker: Keyed[T, K] names the (service, key) pair for resolution (Container.resolve[Keyed[Session, PrimaryKey]]()) and value slot addressing.

struct Keyed[T: Movable & Deinitable, K: AnyType](Movable, Deinitable)

K is an ordinary empty marker struct — no strings, no runtime lookup. See Keyed and qualified registrations.

DefaultKey

Source: mjdi/keyed.mojo

The reserved key for unkeyed registrations: Inject[T] is Inject[T, DefaultKey], so pre-0.10.0 code keeps compiling unchanged.

struct DefaultKey

Registering explicitly under DefaultKey is rejected (MJDI-E023) — it stays the unkeyed lane. See Keyed and qualified registrations.

All

Source: mjdi/multi.mojo

The multi-binding field marker (P2-03): var plugins: All[Plugin] resolves EVERY provider registered for Plugin, in registration order, as a List[Plugin].

struct All[T: Movable & Deinitable](ResolvableField, Defaultable)

No providers yields an EMPTY collection (legitimate; inspect with count_all[T]()); elements require Copyable (MJDI-E028). See Multi-bindings.

count_all

Source: mjdi/container.mojo

Counts the providers registered for T without constructing any: the inspectable shape of a multi-binding.

    def count_all[T: Movable & Deinitable](/docs/0.10.0/self) -> Int

See Multi-bindings.

OptionalInject

Source: mjdi/optional.mojo

The optional dependency marker (P2-04): var db: OptionalInject[Database] resolves to a present/absent wrapper — absence is a runtime present() == False, never a validation failure.

struct OptionalInject[T: Movable & Deinitable, K: AnyType = DefaultKey](
    ResolvableField, Defaultable
)

A PRESENT optional constructs through its provider, so construction failures still propagate and cycles through optional dependencies are still detected. See Optional dependencies.

ProviderDecorator

Source: mjdi/decorator.mojo

The decorator trait (P2-05): resolution_started / resolution_succeeded / resolution_failed hooks (all defaulting to no-ops) that wrap any supported provider via register_decorated[...].

trait ProviderDecorator

Hooks receive the resolution context, so a decorator resolves its own dependencies like any consumer; the wrapped provider's kind, scope, and ownership rules are preserved. See Provider decorators.

register_decorated

Source: mjdi/registry.mojo

Wraps a provider with one or more decorators: register_decorated[T, decorator, scope]() — cross-cutting concerns (metrics, tracing, retries) without touching the service.

    def register_decorated[
        T: Movable & Deinitable,
        D: ProviderDecorator,
        scope: provider_scope = provider_scope.transient,
    ](
        self,
    ) -> ProviderRegistry[DecoratedProvider[ClassProvider[T, scope], D], Self]

Failures propagate unchanged after the failure hook; the graph reports the wrapped registration. See Provider decorators.

Assisted

Source: mjdi/assisted.mojo

The assisted-parameter field marker (P2-07): var connection: Assisted[ConnParam] declares a field the CALLER supplies at construction time; every other field resolves through the validated graph.

struct Assisted[P: Movable & Deinitable](Defaultable, Movable, Deinitable)

Read before population aborts (MJDI-A002). Construct via container.assisted[T](/docs/0.10.0/param). See Assisted injection.

register_assisted

Source: mjdi/registry.mojo

Registers an assisted factory: register_assisted[T, P, factory]() — the factory takes the caller-supplied parameter P plus whatever it resolves itself.

    def register_assisted[
        T: Movable & Deinitable,
        P: Movable & Deinitable,
        factory: def(P) raises thin -> T,
    ](
        self,
    ) -> ProviderRegistry[AssistedProvider[T, P, factory], Self]

Assisted services are transient by design (the factory runs per construction); resolve[T]() on an assisted service is rejected (MJDI-E026). See Assisted injection.

assisted

Source: mjdi/container.mojo

The assisted construction entry point: container.assisted[T](/docs/0.10.0/param) / scope.assisted[T](/docs/0.10.0/param) constructs T with the caller-supplied parameter.

    def assisted[T: Movable & Deinitable, P: Movable & Deinitable](mut self, var param: P) raises -> T

The capability behind DependencyResolver.resolve_assisted (default MJDI-R008). See Assisted injection.

add_provider

Source: mjdi/registry.mojo

Composes a registry bundle (P2-08): add_provider[H, R]() attaches a reusable fragment (a generic function or a named comptime fragment) over any base registry.

def add_provider[
    H: ProviderSpec,
    R: ProviderChain & RuntimeChain & Defaultable & Movable & Deinitable,
]() -> ProviderRegistry[H, R]

Collision policy is the ordinary duplicate rule (MJDI-E004); composition is type-level and immutable. See Registry bundles.

register_factory_with_deps

Source: mjdi/registry.mojo

Declares a factory's dependency metadata (P2-12): register_factory_with_deps[T, factory, D1, D2, D3, scope]() names up to three dependency types the factory resolves, so the graph, validation, and explain_resolution see through the factory.

    def register_factory_with_deps[
        T: Movable & Deinitable,
        factory: def() raises thin -> T,
        D1: AnyType,
        D2: AnyType = NoDep,
        D3: AnyType = NoDep,
        scope: provider_scope = provider_scope.transient,
    ](
        self,
    ) -> ProviderRegistry[
        FactoryProvider[T, factory, scope, provider_origin.register_factory, D1, D2, D3], Self
    ]

An undeclared dependency is an unregistered provider at validation (MJDI-E024 factory-deps variant). See Factory dependency metadata.

child_scope

Source: mjdi/container.mojo

Creates a child scope (P2-10): the child inherits COPIES of what the parent resolved and owns every copy outright — closing the parent never touches the child.

    def child_scope(mut self) raises -> Scope[Self.registry, Self.traced, Self.collect_stats, Self.reentrancy_guard, Self.debug_tracking]

Named scopes: create_scope("request-42"). See Child scopes.


This page is generated: python3 scripts/gen_api_reference.py regenerates it from the library sources; --check verifies the checked-in copy is current.