mjdi

Search documentation

Search the mjdi v0.10.0 documentation

mjdi docsv0.10.0latest

Declaring Dependencies with Inject[T]

Inject[T] is how a service says "I need a T". This document covers the

Source: mjdi/docs/dependency-declaration.md

Inject[T] is how a service says "I need a T". This document covers the marker's API, the rules around it, nested graphs, and one constraint that shapes everyday code: references you read through a marker are immutable views, so mutation happens on owned instances, not through Inject.

The marker

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

A field declared as Inject[T] marks a dependency. The container discovers marker fields by reflecting over the struct's field types, resolves each dependency through the active resolver, and writes a populated wrapper back into the field. The marker conforms to mjdi's internal ResolvableField contract — that is the only coupling between the scanner and the marker, which is why the scanner never inspects Inject's storage layout.

The type bound: T must be Movable and Deinitable — the standard bounds for any value passed around Mojo code. Inject itself is Defaultable, which is what makes two-phase construction possible (every dependency type is acceptable, including ones with required constructor arguments).

Why a wrapper at all

Inject[T] stores an Optional[T]. Storing the dependency directly would require every dependency to be default-constructible, which conflicts with services like Database(url). The Optional-backed marker is always defaultable; "was never resolved" becomes a representable state instead of a crash during construction. The full rationale is design note 1 in Technical investigation.

Reading a dependency: value()

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

value() returns a reference to the resolved dependency. The parentheses are a Mojo 1.2.0 constraint — there is no @property support, so the accessor is a method (deviation 2 in Known limitations).

Unresolved reads abort. Calling value() on a wrapper the container never populated aborts with a precise diagnostic:

mjdi: dependency of type 'UserRepository' was never resolved. Inject fields
are populated by the container; construct instances through
Container.resolve (or Injectable.create) instead of calling the struct
constructor directly.

This is a deliberate loud failure: it means the service was constructed directly (UserService() in application code) instead of being resolved through mjdi. See tests/crash_expected/crash_unresolved_inject.mojo.

The immutable-reference rule

value() hands you an immutable view of the stored dependency. The consequence shows up as a compile error the first time you hit it:

struct TaskService(Injectable):
    var store: Inject[TaskStore]

    def run(self) -> String:
        return self.store.value().add("hello")   # ERROR
error: invalid use of mutating method on rvalue of type 'TaskStore'

Mutating methods (def add(mut self, ...)) need a mutable receiver, and a view obtained through value() is not one. The fix is ownership: resolve the dependency into a local var and mutate that:

def run(self) -> String:
    var store = TaskStore()        # or resolve it at the composition root
    return store.add("hello")      # fine: store is owned

Design services so that what flows through Inject fields is read (find_by_id, render, record), and put mutation at the edge where the instance is owned — usually main(), or the service that constructed the value itself. This is not a mjdi limitation being papered over: it is Mojo's ownership model, and mjdi keeps it visible rather than hiding it. The Patterns page shows the structural answers.

Other marker members

MemberSignaturePurpose
value()def value(ref self) -> ref[...] Self.TThe dependency reference; aborts when unresolved.
is_resolved()def is_resolved(self) -> BoolTrue once the container populated this marker. Useful in tests and in create overrides.
cloned()def cloned(self) -> Self where conforms_to(Self.T, Copyable)A copy of the marker holding a copy of the dependency. Used in copy constructors of Copyable services.

Constructors (for mjdi internals and create overrides):

  • Inject[T]() — unresolved marker (what your __init__(out self) assigns).
  • Inject[T](var value: T) — resolved marker holding value (what a create override assigns after resolving).

Nested graphs

Dependencies are services too, so graphs nest naturally. mjdi resolves the whole chain transitively from a single top-level resolve:

struct SqlGateway(Injectable):
    var config: Inject[AppConfig]

struct OrderRepository(Injectable):
    var gateway: Inject[SqlGateway]

struct OrderService(Injectable):
    var repository: Inject[OrderRepository]

struct HttpController(Injectable):
    var service: Inject[OrderService]

# registry registers all four; the application only resolves HttpController.
var controller = app.resolve[HttpController]()

Two structural notes:

  • Graphs must be acyclic as structs. A struct whose field type eventually contains itself cannot be laid out in memory, and the Mojo compiler rejects it at type-definition time ("attempt to resolve a recursive reference"). mjdi additionally carries a compile-time cycle walk as defense in depth; see Compile-time validation.
  • Diamonds are fine. Two services depending on the same type each get their own resolution of it (transient) or their own copy of the canonical instance (singleton/scoped) — whichever the provider's scope says.

Marker fields vs ordinary fields

struct TaskStore(Injectable):
    var count: Int                       # ordinary field: the constructor sets it,
    def __init__(out self):              # wiring never touches it
        self.count = 0

The rule is simple: the scanner touches only fields whose type conforms to mjdi's ResolvableField contract. In mjdi 0.4 the only conforming type is Inject[T]. Ordinary fields keep whatever value the constructor gave them, which is how services carry derived or initialized state through wiring untouched.

What belongs in an Inject field

  • Types another provider supplies — collaborators, configuration values, shared handles.
  • Not: values only this instance computes (plain fields), references meant to be mutated through (see the immutable-reference rule), or the container itself (mjdi has no service locator; see Patterns).