mjdi

Search documentation

Search the mjdi v0.10.0 documentation

mjdi docsv0.10.0latest

mjdi Usage Guide

This guide describes the actual implemented behavior of mjdi on Mojo 1.2.0.

Source: mjdi/docs/usage.md

This guide describes the actual implemented behavior of mjdi on Mojo 1.2.0. Compiler constraints that shape the API are summarized inline and detailed in docs/known-limitations.md and docs/technical-investigation.md.

1. Declaring injectable types

Conform a struct to Injectable and declare dependencies with Inject[T] fields:

from mjdi import Injectable, Inject

struct UserRepository(Injectable):
    def find_by_id(self, user_id: Int) -> String:
        return String("User-") + String(user_id)

struct UserService(Injectable):
    var repository: Inject[UserRepository]

    def get_user(self, user_id: Int) -> String:
        return self.repository.value().find_by_id(user_id)

Rules for the default construction path:

  • Injectable extends Defaultable, so the struct must be default-constructible. Give it an __init__(out self) that default- initializes every field; Inject fields start unresolved and are populated by the container.
  • Read a dependency with self.field.value() — the parentheses are a Mojo 1.2.0 constraint (there is no @property support yet).
  • Reading value() on a marker the container never populated aborts with a clear diagnostic: it means the service was constructed directly instead of being resolved through mjdi.
  • A service may also declare ordinary (non-Inject) fields; they keep the values the constructor set. Only marker fields are touched by the container.

2. Registering providers

Registration is compile-time and immutable: every call returns a new registry whose type encodes the provider set.

from mjdi import Registry
from mjdi.provider import provider_scope

comptime app_registry = (
    Registry()
    .register[UserRepository]()                                # class, transient
    .register[Logger, provider_scope.singleton]()              # class, singleton
    .register[UserService]()                                   # class, transient
)

Class providers

.register[T]() constructs T through its Injectable contract. T must conform to Injectable — a non-conforming type is rejected with a diagnostic naming the type.

Value providers

A value provider supplies an externally created value. The compile-time registry records only the kind; the runtime value is supplied per container:

struct Config(Copyable):
    var url: String
    def __init__(out self, var url: String):
        self.url = url^
    def __init__(out self, *, copy: Self):
        self.url = copy.url

comptime reg = Registry().register_value[Config]()
var app = Container[type_of(reg)]()
app.set_value[Config](Config("db://prod"))

T must be Copyable (consumers receive copies). Resolving before calling set_value raises a runtime error; set_value on a type that is not a value provider is a compile-time error. Scopes copy the container's configured values at create_scope() time.

Factory providers

def make_config() raises -> Config:
    return Config("db://from-factory")

comptime reg = Registry().register_factory[Config, make_config]()

The factory is invoked at runtime. With the default transient scope the factory runs once per resolution; a scope parameter enables cached products — .register_factory[Config, make_config, provider_scope.singleton]() constructs once per container and hands out copies (requires Config to be Copyable). Factories must not capture mutable state; a factory that raises propagates the error to the resolver.

Aliases

comptime reg = (
    Registry()
    .register[SqlUserRepository]()
    .register_alias[UserRepository, SqlUserRepository]()
)

Under Mojo's value type system there is no subtyping, so an alias cannot hand out an instance of a different type. An mjdi alias binds the requested type to the lifetime configuration of the target's provider: resolving UserRepository constructs UserRepository through its own contract and caches it with the effective scope (singleton/scoped/transient) that the target resolves to. The target must be a registered class provider and the aliased type must be Injectable; because aliases bind to class providers only, alias cycles are impossible by construction. To share an implementation between types, prefer composition:

struct UserRepository(Injectable):
    var impl: Inject[SqlUserRepository]

Third-party types (the use family)

Types you do not own cannot conform to Injectable (Mojo declares trait conformance at the type-definition site), so registration for them uses the use_* family — same descriptors, same validation, same diagnostics as the register_* equivalents:

comptime reg = (
    Registry()
    .use_value[ExtConfig]()                                  # value provider
    .use_provider[ExtConn, connect_ext]()                    # transient
    .use_provider[ExtPool, open_pool, provider_scope.singleton]()  # cached
)

use_value[T] matches register_value[T] (T: Copyable, value supplied via set_value); use_provider[T, make_t] matches register_factory and takes the same optional scope parameter (cached scopes require T to be Copyable). Third-party types become full graph citizens: your services declare Inject[ExtConfig]-style fields and compile-time validation checks them like any other dependency. The complete guide — including the alias and dependency-declaration boundaries — is docs/third-party.md.

Linear services

Resources that must be used exactly once and released explicitly — leases, transactions, locks — are declared as linear services: annotate the struct with @__annotation(mjdi_linear), conform it to LinearService, and register it through the linear overload of register[T]() — selected by the LinearService trait bound and kept disjoint from the regular overload by its Movable & Deinitable trait bounds (a linear service conforms to neither). Consume it with the visitor overload container.resolve[T](/docs/0.10.0/visitor): mjdi constructs the instance in place, lends it to the visitor exactly once, and calls the service's destroy(deinit self) before the call returns. Linear types cannot be copied, moved, or cached, so the value-returning resolve[T]() overload and the cached lifetimes reject them — the compiler enforces that before mjdi's own diagnostics apply. The complete guide is docs/linear-services.md.

3. Resolving from the container

var app = Container[type_of(app_registry)]()
var service = app.resolve[UserService]()
  • Container[type_of(registry)] — the type_of spelling is required because the registry is a compile-time value (docs/known-limitations.md, deviation 1).
  • Resolution is type-based; there are no string tokens.
  • Missing providers are rejected at compile time, when the container is constructed (validation) or when the resolution is elaborated.
  • Constructing the container runs the full graph validation: missing providers, duplicate registrations, lifetime conflicts, and alias validity are rejected before any application code executes.

4. Scopes

var scope = app.create_scope()
var scoped_service = scope.resolve[RequestState]()
scope.close_scope()
  • Scoped providers (provider_scope.scoped) cache one canonical instance per scope; they cannot be resolved directly from the container.
  • create_scope() copies the container's value slots into the scope, so value-provided dependencies resolve identically inside it; later set_value calls on the container do not affect existing scopes.
  • Singleton and transient providers resolved through a scope are cached or created in the scope (documented deviation from per-container singletons; see docs/known-limitations.md).
  • close_scope() releases every instance cached in the scope. Value slots survive; they are configuration, not lifecycle state.

Lifecycle hooks. Services that conform to InjectableLifecycle (along side Injectable) get post_construct after mjdi wires them, and pre_destruct before mjdi releases a cached canonical instance — at close_scope() for a scope, and at Container.close() for the container's cached singletons (re-constructed on the next resolve). Both hooks are required by the trait; full rules in Lifecycle hooks.

struct Session(Injectable, InjectableLifecycle):
    def post_construct(mut self) raises:   # after wiring
        ...
    def pre_destruct(mut self):            # before close_scope() drops it
        ...

5. Custom construction

Override create when automatic construction is unsuitable:

struct CustomService(Injectable):
    var repo: Inject[PlainRepo]

    @staticmethod
    def create[R: DependencyResolver](mut r: R) raises -> Self:
        var instance = Self()
        instance.repo = Inject[PlainRepo](PlainRepo())
        return instance^

The override can ignore its Inject fields entirely (as above) or use resolve_dependencies[T](/docs/0.10.0/r) to reuse the default machinery. Types that cannot be default-constructed at all should be provided through value or factory providers instead.

6. Error model

mjdi uses one strategy per failure class and does not mix them:

Failure classMechanismExample diagnostic
Missing providerCompile-time (comptime assert at container construction)mjdi: no provider is registered for dependency 'Database' required by 'UserService'
Duplicate registrationCompile-timemjdi: duplicate provider registration for 'ServiceA'
Struct-level cyclesCompile-time (the Mojo compiler rejects recursive struct definitions)attempt to resolve a recursive reference to ...
Singleton depending on scopedCompile-timemjdi: invalid lifetime relationship: singleton provider ...
Scoped resolved from containerCompile-time check + runtime raise at resolutionmjdi: 'X' is registered with the scoped lifetime and can only be resolved through a Scope
Value provider without a valueRuntime raisemjdi: 'Config' is registered as a value provider but no value has been provided
Factory failureRuntime raise (propagated)the factory's own error
Unresolved Inject.value()Runtime abortmjdi: dependency of type 'X' was never resolved
Non-Copyable singleton/scoped/value providerCompile-timemjdi: ... requires the provided type to conform to Copyable

7. Complete examples

See examples/e2e_example.mojo — the full walkthrough from declaring services to resolving and calling them — and the examples/ directory for ten tested example applications, one per mjdi capability (wiring, every provider kind, all three lifetimes, custom construction, and a mixed-providers capstone). The tests/ directory contains a tested example of every provider kind, scope behavior, and error class.