mjdi

Search documentation

Search the mjdi v0.10.0 documentation

mjdi docsv0.10.0latest

The Injectable Contract

Injectable is the construction contract that lets mjdi build and wire a

Source: mjdi/docs/injectable.md

Injectable is the construction contract that lets mjdi build and wire a struct automatically. This document covers the contract itself, the two-phase construction it enables, the requirements it places on your structs, and how to override the default construction path. The dependency marker your fields use, Inject[T], has its own document: Dependency declaration.

The contract

trait Injectable(Defaultable, Movable, Deinitable):
    @staticmethod
    def create[R: DependencyResolver](mut r: R) raises -> Self:
        var instance = Self()
        populate_inject_fields[Self, R](instance, r)
        return instance^

Conforming to Injectable opts a struct into mjdi's default construction path: default-construct the instance, resolve every Inject field through the active resolver, and return the wired instance. Because the trait inherits Defaultable, Movable, and Deinitable, every conforming struct already satisfies the bounds the rest of the library places on services.

The container never calls your constructor with arguments. It calls create, and the default create does the two-phase dance above. You can override it (see Overriding create).

Requirements on conforming structs

RequirementWhyHow to satisfy
Default-constructibleInjectable extends Defaultable; phase one is Self().Provide def __init__(out self): that default-initializes every field. Inject fields start unresolved, so they never block this.
Dependencies declared as Inject[T] fieldsPhase two populates exactly those fields via reflection.var repository: Inject[UserRepository]
Movable / DeinitableInherited bounds; Mojo synthesizes them for ordinary structs.Nothing to do for structs with plain fields.
Copyable — only if registered singleton or scopedCached lifetimes hand out copies.Conform to Copyable and write the copy constructor; use Inject.cloned() for marker fields. See Ownership and memory.

Notes that trip people up:

  • Fieldless structs need an explicit constructor. Mojo 1.2.0 does not synthesize a zero-argument __init__ for a struct with no fields. Add def __init__(out self): pass.
  • Ordinary (non-Inject) fields are preserved. The scanner only touches marker fields, so values your constructor set — a counter starting at zero, a default prefix — survive wiring.
  • A struct that cannot be default-constructed at all (it needs arguments) should not conform to Injectable; provide it with a factory or value provider instead. It can still appear in graphs — as the target of another service's Inject field — because value and factory providers do not use the construction contract.

Two-phase construction

Why default-construct first? Because Inject[T] is always defaultable regardless of what T is — it stores an Optional[T] that starts empty. That combination (default-construct, then overwrite) is the only safe reflective construction on Mojo 1.2.0: arbitrary-argument reflective construction is not expressible in safe Mojo (tuple-splatting into fixed-arity callees, pack concatenation, and passing __init__ as a function value are all rejected by the compiler — findings 19–22 in Technical investigation).

The runtime cost is what you would expect: one construction plus one field write per dependency, with all the dispatch resolved at compile time. The design rationale is in Architecture.

Overriding create

Override the static create method when the default path is unsuitable. Two standard shapes exist; both are verified in the examples and tests.

Shape 1: resolve explicitly, derive state

From examples/custom_construction/app.mojo — the service derives a clamped retry budget that cannot be expressed as a plain field:

struct HttpGateway(Injectable):
    var config: Inject[RetryConfig]
    var effective_attempts: Int

    def __init__(out self):
        self.config = Inject[RetryConfig]()
        self.effective_attempts = 0

    @staticmethod
    def create[R: DependencyResolver](mut r: R) raises -> Self:
        var instance = Self()
        instance.config = Inject[RetryConfig](r.resolve[RetryConfig]())
        instance.effective_attempts = instance.config.value().max_attempts
        if instance.effective_attempts > 5:
            instance.effective_attempts = 5
        return instance^

The override receives the active DependencyResolver and may resolve anything registered. r.resolve[RetryConfig]() follows the same rules as container resolution (provider lookup, lifetime handling); wrapping the result in Inject[RetryConfig](...) stores it in the marker field.

Shape 2: ignore the fields entirely

A create override may not use its Inject fields at all — it is free to construct the service however it likes:

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

This is the escape hatch for services that want some fields wired by hand. The fields remain declared (so the graph documents them), but populate differently. Keep in mind that compile-time validation still checks declared Inject fields against the registry — an override does not exempt you from registering what you declare.

Reusing the default machinery

resolve_dependencies[T](/docs/0.10.0/r) is the public entry point the default create uses. An override can call it to get the default wiring and then adjust the result:

@staticmethod
def create[R: DependencyResolver](mut r: R) raises -> Self:
    var instance = resolve_dependencies[Self, R](/docs/0.10.0/r)
    var attempts = instance.config.value().max_attempts
    if attempts > 5:
        attempts = 5
    instance.effective_attempts = attempts
    return instance^

resolve_dependencies is exported from the package root: from mjdi import resolve_dependencies.

When create is invoked

  • Transient class providers: on every resolve[T]() (or nested construction) — the override runs each time.
  • Singleton / scoped class providers: once per container/scope, when the canonical instance is first constructed; every later consumer receives a copy, not a new create run. Deriving "per-construction" state in a singleton means it is computed once.
  • Value and factory providers: never — they bypass the construction contract entirely.

Injectable + Copyable

Services registered singleton or scoped must be Copyable, and their copy constructor must copy Inject fields with cloned():

struct Inventory(Injectable, Copyable):
    var config: Inject[StoreConfig]
    var stock: Int

    def __init__(out self):
        self.config = Inject[StoreConfig]()
        self.stock = 100

    def __init__(out self, *, copy: Self):
        self.config = copy.config.cloned()
        self.stock = copy.stock

Forgetting cloned() (or hand-copying the Optional inside the marker) is the classic mistake — the compiler will tell you the marker is not copyable without it. The full copy-constructor recipe is in Ownership and memory.

Lifecycle hooks: InjectableLifecycle

A service can opt into a construction and release protocol by also conforming to InjectableLifecycle:

struct Inventory(Injectable, InjectableLifecycle):
    var store: Inject[StoreConfig]

    def __init__(out self):
        self.store = Inject[StoreConfig]()

    def post_construct(mut self) raises:
        # Runs inside the default create, after every Inject field is
        # populated — reading self.store here is safe.
        ...

    def pre_destruct(mut self):
        # Runs inside close()/close_scope() before mjdi drops the cached
        # canonical instance.
        ...

Both hooks are required (the trait has no defaults). post_construct fires at every construction mjdi performs — transient resolutions, and the canonical construction of singleton/scoped providers and alias sources; pre_destruct fires when mjdi releases a cached canonical instance through Container.close() or Scope.close_scope(). Transient instances (which the caller owns), consumer copies, value-provider values, and factory products' construction are deliberately outside the protocol; a create override owns its own hook invocation. The complete invocation matrix, the raising rules, and the testing patterns: Lifecycle hooks.

Common questions

Can a service conform to Injectable and also be provided by a factory? Yes, but pointlessly — factories bypass create. Pick one path.

Can create resolve things that are not declared as fields? Yes; r.resolve[T]() works for any registered type. Declare what the struct owns as fields; resolve transient needs directly if that is more honest.

Do I need Injectable on every type in the graph? No — only on types provided by class providers. Value- and factory-provided types never go through the contract (aliases additionally require the aliased type to be Injectable, since aliases construct the requested type through it).

Does validation check Inject fields my create override ignores? Yes. The graph is built from declared fields, not from what create reads — declared-but-unregistered dependencies still fail compilation.