mjdi

Search documentation

Search the mjdi v0.10.0 documentation

mjdi docsv0.10.0latest

Getting Started

This guide takes you from a bare machine to a running, dependency-injected

Source: mjdi/docs/getting-started.md

This guide takes you from a bare machine to a running, dependency-injected Mojo application. It covers installing the compiler, adding mjdi to a project, the smallest useful program, and the commands you will use every day (examples, tests, coverage).

1. Prerequisites

mjdi targets Mojo 1.2.0 and is tested against mojo 1.2.0 (2016d0cd). The compiler is distributed on PyPI by Modular Inc:

python3 -m pip install mojo==1.2.0
mojo --version   # mojo 1.2.0 (2016d0cd)

Mojo 1.2.0 notes that matter to mjdi users:

  • mojo test does not exist yet — mjdi's test suite is a set of standalone programs driven by a shell script (see Testing).
  • mojo package is deprecated in favor of mojo precompile (see below).
  • The fn keyword is gone; examples use def.

2. Get mjdi

mjdi is a source package. Copy the mjdi/ package directory into your project (or clone this repository and add it to your import path):

your-project/
├── mjdi/            <- the mjdi package (10 Mojo modules)
├── your_code.mojo
└── ...

Optionally precompile the package once to speed up repeated builds:

mojo precompile mjdi -o mjdi.mojoc

mojo package is deprecated in Mojo 1.2.0; mojo precompile produces the same .mojoc artifact.

3. Your first program

Create hello_di.mojo next to the mjdi/ directory:

from mjdi import Container, Injectable, Inject, Registry


struct MessageRenderer(Injectable):
    """The innermost service: no dependencies of its own."""

    def render(self, name: String) -> String:
        return String("Hello, ") + name + String("!")


struct GreetingService(Injectable):
    """Declares its dependency with an Inject field."""

    var renderer: Inject[MessageRenderer]

    def greet(self, name: String) -> String:
        return self.renderer.value().render(name)


def main() raises:
    # Compile-time registration: the provider set is encoded in the type.
    comptime app_registry = (
        Registry()
        .register[MessageRenderer]()
        .register[GreetingService]()
    )

    # The container is specialized for that registry. Constructing it runs
    # the full compile-time graph validation (missing providers, duplicate
    # registrations, lifetime conflicts).
    var app = Container[type_of(app_registry)]()

    # One resolve wires the whole chain.
    var service = app.resolve[GreetingService]()
    print(service.greet("mojo"))    # Hello, mojo!

Run it (from the directory that contains mjdi/):

mojo run -I . hello_di.mojo

Expected output:

Hello, mojo!

Three things to notice — they are the whole library:

  1. Dependencies are declared with types (var renderer: Inject[MessageRenderer]), not names or strings.
  2. Providers are registered at compile time (comptime app_registry = Registry()...); the registry is an immutable value whose type encodes the provider set.
  3. Resolution happens at runtime (app.resolve[GreetingService]()), and everything that can be checked without running — missing providers, cycles, lifetime conflicts — is checked before your code executes.

If you forget a registration — say you delete .register[MessageRenderer]() — the program no longer compiles:

error: ... constraint failed: mjdi: no provider is registered for dependency
'MessageRenderer' required by 'GreetingService'. Register it with
Registry().register[MessageRenderer]() (or a value/factory/alias provider)
before creating a Container.

The full catalog of diagnostics lives in Diagnostics.

4. Run the examples

The repository ships ten runnable example applications, one per capability. From the project root:

mojo run -I . examples/basic_wiring/app.mojo        # minimal wiring
mojo run -I . examples/value_providers/app.mojo     # configuration via set_value
mojo run -I . examples/factory_providers/app.mojo   # construction owned by a function
mojo run -I . examples/alias_bindings/app.mojo      # binding one type to another's lifetime
mojo run -I . examples/singleton_lifecycle/app.mojo # one construction per container
mojo run -I . examples/scoped_sessions/app.mojo     # per-unit-of-work instances
mojo run -I . examples/custom_construction/app.mojo # overriding Injectable.create
mojo run -I . examples/layered_app/app.mojo         # a four-level dependency chain
mojo run -I . examples/transient_pipelines/app.mojo # fresh instances per resolve
mojo run -I . examples/mixed_providers_app/app.mojo # capstone: every kind at once

Each example prints a deterministic report and has a dedicated test file. The Examples guide explains what each one teaches.

5. Run the test suite

The suite covers unit tests, compile-fail fixtures (which must fail to compile, with a specific diagnostic), crash-expected fixtures, the end-to-end example, and golden-output runs of all ten examples:

bash scripts/run_tests.sh

On a healthy checkout you should see === summary: 54 passed, 0 failed ===.

6. Check coverage

Mojo 1.2.0 has no coverage instrumentation, so mjdi measures static API-surface coverage: every public declaration must be referenced from the executable artifacts (tests, fixtures, examples). Both gates are 95%; both suites currently sit at 100%:

python3 scripts/coverage_report.py     # library API surface: 265/265
python3 scripts/example_coverage.py    # example declarations: 88/88

The methodology and its limits are described in Testing.

7. Using mjdi in your own project

The pattern from the first program scales directly:

  • declare services as structs conforming to Injectable with Inject[T] fields,
  • build one comptime registry for the application (the composition root),
  • construct Container[type_of(app_registry)]() once, resolve what you need, and pass values — not the container — to the rest of the code.

From here: