mjdi

Search documentation

Search the mjdi v0.10.0 documentation

mjdi docsv0.10.0latest

Providers: The Four Kinds

A provider answers "how do we make a T?" for one registered service type.

Source: mjdi/docs/providers.md

A provider answers "how do we make a T?" for one registered service type. mjdi has four kinds — class, value, factory, and alias — each with distinct semantics, constraints, and failure modes. This page is the complete reference for all four; the scope (lifetime) axis is covered in Scopes and lifetimes.

Choosing a kind

SituationUse
The type is a struct that can be default-constructed and wants its Inject fields wiredClass provider
The value comes from outside the graph — CLI args, parsed env, a config object built in main()Value provider
Construction needs logic the Injectable contract cannot express, or the type cannot be default-constructedFactory provider
The type comes from a library you do not own and cannot conform to InjectableThe use_* family — see Third-party structures
One type should be resolved with another type's lifetime configurationAlias provider

Kinds are also queryable at compile time — see Introspection at the end of this page.

Class providers

comptime app_registry = (
    Registry()
    .register[UserRepository]()                          # transient (default)
    .register[Logger, provider_scope.singleton]()        # singleton
    .register[Session, provider_scope.scoped]()          # scoped
)

A class provider constructs T through its Injectable contract: default-construct, then populate every Inject field. The scope parameter defaults to provider_scope.transient; singleton and scoped variants cache one canonical construction per container/scope and hand out copies (so T must be Copyable — Scopes and lifetimes).

Constraints and their diagnostics:

  • T must conform to Injectable. A non-conforming class provider is rejected with a compile-time diagnostic when the container is constructed (and at construction dispatch: "class provider 'T' does not conform to the Injectable trait").
  • Registering the same type twice — under any kind — is rejected at compile time: "duplicate provider registration for 'T'". Aliases are the deliberate exception (they are the override mechanism); see Aliases.

Value providers

comptime app_registry = Registry()
    .register_value[StoreConfig]()

var app = Container[type_of(app_registry)]()
app.set_value[StoreConfig](StoreConfig("usd", 80))
var config = app.resolve[StoreConfig]()

A value provider supplies an externally created value. The compile-time registry only records the kind — a compile-time registry cannot store runtime values (deviation 4 in Known limitations) — and the application supplies the actual value per container with set_value[T](/docs/0.10.0/v).

Semantics and rules:

  • T must be Copyable; consumers receive copies of the stored value.

  • set_value may be called again later. Transient consumers constructed after the call observe the new value; singleton consumers do not (they snapshotted the value at construction — see the tutorial).

  • container.has_value[T]() reports whether a value has been supplied.

  • Resolving before set_value raises at runtime:

    mjdi: 'T' is registered as a value provider but no value has been
    provided. Call container.set_value[T](/docs/0.10.0/value) before resolving it.
    
  • set_value on a type that is not a value provider (or is not registered at all) fails at compile time.

  • Scopes receive a copy of the container's configured values at create_scope() time; later container set_value calls do not affect existing scopes. A scope can also set_value for itself, which overrides its mirrored slot (see Scopes and lifetimes).

  • Value slots are configuration, not lifecycle state: they survive close_scope() and are replaced only by set_value.

Factory providers

def make_id_generator() raises -> IdGenerator:
    var generator = IdGenerator()
    return generator^

comptime app_registry = Registry()
    .register_factory[IdGenerator, make_id_generator]()

A factory provider registers a plain function as the construction logic for T. The function is a compile-time parameter of the registration; the registry stores the function, never calls it — invocation happens at runtime.

Rules:

  • The default lifetime is transient; cached scopes are supported. With the default scope the factory runs once per resolution. Pass a scope to cache the product: .register_factory[T, make_t, provider_scope.singleton]() invokes the factory once per container and hands out copies of the canonical product (requires T to be Copyable — the same rule as cached class providers, checked at registration); scoped caches one product per Scope and must be resolved through a scope. The factory is never invoked at registration or container construction — only at the first resolution that needs the product.
  • No capturing mutable state. The function is registered at compile time and may be invoked from any container or scope built from that registry.
  • The factory may raise; the error propagates to the caller of resolve (verified by tests/test_factories.mojo).
  • The function type uses Mojo 1.2.0's thin convention: def() raises thin -> T. This is what the registry's signature requires; plain def functions qualify automatically.
  • The produced type does not need to conform to Injectable — the factory owns construction. It does need Movable & Deinitable, and Copyable for cached scopes.
  • Factory-mediated cycles (a factory that resolves a service that resolves the factory's product) cannot be detected statically — factories are opaque at compile time — and will recurse at runtime. See Compile-time validation.

Third-party structures: the use family

Types you do not own — external or third-party structs — cannot add the Injectable conformance mjdi's class path requires: Mojo declares trait conformance at the type-definition site, so a struct from another library cannot be retrofitted. The use_* family is the registration spelling for exactly these types. Semantics are identical to the register_* equivalents (same descriptors, same validation, same diagnostics), so wiring reads consistently regardless of who owns the type:

from mjdi import Registry
from mjdi.provider import provider_scope

comptime app_registry = (
    Registry()
    .use_value[ExtConfig]()                                     # value provider
    .use_provider[ExtConn, connect_ext]()                       # transient factory
    .use_provider[ExtPool, open_ext_pool, provider_scope.singleton]()  # cached factory
)
MethodEquivalentRequirements
.use_value[T]().register_value[T]()T: Copyable; the value is supplied per container via set_value[T].
.use_provider[T, make_t]().register_factory[T, make_t]()T: Movable & Deinitable; make_t owns construction (transient).
.use_provider[T, make_t, provider_scope.singleton]()cached factoryadditionally T: Copyable — canonical product cached per container, copies handed out.
.use_provider[T, make_t, provider_scope.scoped]()cached factoryadditionally T: Copyable; must be resolved through a Scope.

The third-party types become full graph citizens: your own Injectable services declare Inject[ExtConfig], Inject[ExtConn], Inject[ExtPool] fields, and compile-time validation checks those dependencies exactly like any other (a missing use_* registration fails the build with the same consumer-aware diagnostic). Verified end to end by tests/test_use_providers.mojo.

Two boundaries, by design:

  • Aliases cannot start at a third-party type. register_alias constructs the aliased type through its Injectable contract, so the alias source must be Injectable. To give an external type a specific lifetime, register it with use_provider and that scope directly — the observable behavior is the same.
  • Third-party types cannot declare Inject fields (they do not conform to mjdi traits). Consumption flows one way: your services declare dependencies on third-party types; third-party types never declare dependencies on yours.

Alias providers

comptime app_registry = (
    Registry()
    .register[SqlUserRepository, provider_scope.singleton]()
    .register_alias[UserRepository, SqlUserRepository]()
)

An alias binds requests for From to the provider registered for To. Under Mojo's value type system there is no subtyping, so an alias cannot hand out an instance of a different type. What it binds instead is the lifetime configuration: resolving UserRepository constructs UserRepository through its own Injectable contract and caches it with the effective scope that To's provider resolves to.

This surprises people coming from reference-semantics DI frameworks, so the verified behavior deserves stating plainly (from tests/test_aliases.mojo):

  • app.resolve[UserRepository]() returns an instance of UserRepository — the requested type — not of SqlUserRepository.
  • If SqlUserRepository is registered singleton, resolving the alias caches the canonical UserRepository per container and hands out copies; scope_of[UserRepository]() reports singleton — the alias inherits the target's effective scope.
  • Aliasing an already-registered type overrides it (last registration wins). Aliases skip the duplicate check on purpose; this is the documented override mechanism.

Validity rules (compile-time, at registration and again at container construction):

  • To must already be registered — "alias for 'From' targets 'To', which is not registered in this registry."
  • To must be a class provider — aliasing a value or factory provider is rejected ("cannot bind to ... because the target is not a class provider"). Because aliases bind to class providers only, alias cycles are impossible by construction; a depth-limited chain walk remains as defense in depth.
  • From must conform to Injectable — "alias source 'From' does not conform to the Injectable trait."

Aliases vs composition

For "program against an abstraction, plug in an implementation," prefer composition — it is the honest shape under value semantics:

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

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

The abstraction is a plain struct; the implementation is a dependency; swapping implementations means registering a different provider for SqlUserRepository. Use an alias when what you actually want is lifetime binding for a concrete type (the verified semantics above), not polymorphism.

Introspection

The registry chain answers compile-time queries about its providers. These are the same queries the validator and the container dispatch through:

QueryReturns
Q.provides[T]()True when some provider in the chain provides T.
Q.kind_of[T]()The provider kind (class_provider / value_provider / factory_provider / alias_provider).
Q.scope_of[T]()The effective lifetime, following aliases to their targets.

where Q is the registry's type (type_of(app_registry)). Example 10 (examples/mixed_providers_app/app.mojo) builds a report from exactly these queries. One mechanical note: Mojo 1.2.0 enums have no __eq__, so compare discriminants:

from mjdi import provider_kind

comptime kind = Q.kind_of[T]()
comptime if kind._get_enum_discriminant() == provider_kind.value_provider._get_enum_discriminant():
    return String("value")

The public enums live in mjdi.provider (provider_scope, provider_kind) and are re-exported from the package root.

Error behavior at a glance

MistakePhaseDiagnostic starts with
Register the same type twice (class/value/factory)Compile timemjdi: duplicate provider registration for '...'
Class provider for a non-Injectable typeCompile timemjdi: class provider '...' does not conform to the Injectable trait
register_value[T] with non-Copyable TCompile timemjdi: value provider '...' requires the provided type to conform to Copyable
Singleton/scoped class provider with non-Copyable TCompile timemjdi: singleton class provider '...' requires the provided type to conform to Copyable
Cached factory scope (singleton/scoped) with non-Copyable TCompile timemjdi: singleton factory provider '...' requires the provided type to conform to Copyable
Alias to an unregistered typeCompile timemjdi: alias for '...' targets '...', which is not registered
Alias to a non-class providerCompile timemjdi: alias '...' cannot bind to '...'
Resolve a value provider whose value was never setRuntime raisemjdi: '...' is registered as a value provider but no value has been provided
Factory raisesRuntime raisethe factory's own error

The full message text for every entry is in Diagnostics.