mjdi docsv0.10.0latest
Lifecycle hooks: InjectableLifecycle
InjectableLifecycle is the opt-in lifecycle contract for services mjdi
Source: mjdi/docs/lifecycle.md
InjectableLifecycle is the opt-in lifecycle contract for services mjdi
constructs and caches. Conforming a struct to it (alongside Injectable)
gives it two hooks: post_construct, invoked once the instance is fully
constructed and wired, and pre_destruct, invoked immediately before mjdi
releases a cached instance the container owns. This document covers the
contract, the exact invocation points, what is deliberately excluded, and
how to test lifecycle services.
mjdi 0.7.0 is the release these documents describe; see
changelog.md for the release history.
The contract
trait InjectableLifecycle:
def post_construct(mut self) raises:
...
def pre_destruct(mut self):
...
Both methods are required — the trait provides no default
implementations, so a struct that declares InjectableLifecycle without
implementing either hook does not compile (the compiler enforces trait
conformance at the definition site; the suite pins this with the
cf_lifecycle_missing_pre_destruct fixture). Conform alongside
Injectable:
struct Inventory(Injectable, InjectableLifecycle):
var store: Inject[StoreConfig]
var cache: Cache
def __init__(out self):
self.store = Inject[StoreConfig]()
self.cache = Cache.empty()
def post_construct(mut self) raises:
# Every Inject field is resolved by now.
self.cache = Cache.warm(self.store.value().items)
def pre_destruct(mut self):
self.cache.flush()
(The examples in this document follow the library's test suite —
tests/test_lifecycle.mojo — which exercises every rule below on the
target compiler. Signatures must match the trait exactly, including the
mut self receiver and the raises flag on post_construct.)
post_construct: after wiring, before use
The default Injectable.create runs three phases: default-construct the
instance, populate every Inject field through the active resolver, then —
when the struct conforms to InjectableLifecycle — invoke post_construct
on the fully wired instance before it is returned or cached.
Reading a resolved dependency marker inside the hook is therefore safe, and is the clearest way to document the ordering:
def post_construct(mut self) raises:
# Reading the marker proves the hook runs after the wiring phase:
# reading an unresolved marker aborts the program.
self.stamp = String("wired:") + self.config.value().label
The hook may raise. The error propagates out of resolve, the half-built
instance is discarded, and nothing is cached — a singleton whose
post_construct fails is simply retried on the next resolution.
post_construct fires for every construction mjdi performs:
| Provider kind | Lifetime | post_construct runs |
|---|---|---|
| Class | transient | On every resolve[T]() — a fresh construction each time. |
| Class | singleton | Once per container, when the canonical instance is constructed. |
| Class | scoped | Once per scope, when the canonical instance is constructed. |
| Alias (any effective scope) | — | Once per canonical construction of the alias source, which goes through its own create. |
| Value | — | Never — mjdi does not construct value-provider values. |
| Factory | — | Never — the factory owns construction end to end. |
pre_destruct: before mjdi releases a cached instance
mjdi does not observe Mojo's implicit deinitialization. Instead, cached
instances are released through explicit release calls, and that is
where pre_destruct runs — before the slot drops the value, so the
instance is fully usable inside the hook:
Scope.close_scope()— releases everything cached in that scope: scoped canonical instances and singletons resolved through the scope (singletons cache in the scope; see Scopes and lifetimes).Container.close()— releases the container's cached canonical instances (singletons, cached alias sources, cached factory products). Afterclose(), the next resolution re-constructs; value slots survive, exactly as withclose_scope().
The hook receives the instance mutably and must not raise — the release
paths (close() / close_scope() return None) cannot propagate errors.
Flush buffered state, close handles, log; keep failures observable but
non-fatal.
Implicit teardown does not invoke the hooks. Dropping a container or
scope without calling close() / close_scope() releases cached instances
through Mojo's ordinary field deinitialization with no lifecycle
notification. Call the explicit release method when your services declare
lifecycle hooks — this keeps the release point auditable in your code, the
same principle behind the linear service's mandatory
destroy(deinit self).
What is deliberately excluded
- Transient instances are returned by value and owned by the caller;
their release is ordinary Mojo deinitialization, which mjdi does not
observe. A transient service's
pre_destructis never called by mjdi. - Consumer copies of singleton/scoped canonical instances are ordinary values (value semantics); only the canonical instance mjdi caches receives the hooks.
- Value-provider slots hold application configuration, not lifecycle
state; they survive
close_scope()and are exempt frompre_destruct. - Cached factory products get
pre_destructat release (mjdi owns the release) but neverpost_construct(the factory, not mjdi, performed the construction). - Linear services have their own release contract —
LinearService.destroy(deinit self), invoked by the visitor overload ofresolve— and are notInjectableconformers at all.
Copy semantics
Cached lifetimes hand out copies of the canonical instance (Mojo value
semantics). A copy is made after post_construct ran, so the copy carries
the post-constructed state; the copy's own release at the consumer is
ordinary deinitialization without hooks. Services with Inject fields must
clone markers in their copy constructors with Inject.cloned() — see
Ownership and memory.
Custom create overrides
The hook lives inside the default create. An override replaces the
whole construction path, so it owns any lifecycle behavior too:
@staticmethod
def create[R: DependencyResolver](mut r: R) raises -> Self:
var instance = resolve_dependencies[Self, R](/docs/0.10.0/r) # default wiring only
instance.post_construct() # honor the hook yourself
return instance^
A conforming struct whose create override never calls post_construct
simply never gets the construction hook — mjdi will not inject it behind
your back. (The release hook is unaffected: it belongs to the slots, not
to create.)
Testing lifecycle services
The library's own suite observes post_construct through resolved state
(the hook reads an Inject marker, which would abort if the wiring had not
finished) and observes pre_destruct through print markers that
scripts/run_tests.sh counts, plus behavioral release proof: after
close() / close_scope(), the next resolution re-constructs and sees
newly supplied values. The same two patterns work in application tests:
var r1 = app.resolve[CachedService]()
assert_equal(r1.initialized, True, "post_construct ran")
app.close()
app.set_value[AppConfig](AppConfig("db-three"))
assert_equal(
app.resolve[CachedService]().stamp(),
"wired:db-three",
"close() released the canonical instance; the next resolve re-constructs",
)
Common questions
Can a struct conform to InjectableLifecycle without Injectable?
Yes, and it compiles — but nothing invokes the hooks: construction hooks
live in the default Injectable.create, and cached-class/alias release is
the only pre_destruct path, which requires the struct to be constructible
through the contract. Value- and factory-provided types that conform get
only the cached-product release hook. Conform to both traits for the full
protocol.
Does close() invalidate resolved copies?
No. Copies already handed out are independent values owned by their
consumers. close() (and the hook) affect only the canonical instance the
container caches.
What happens if I close() twice, or call close_scope() on an empty
scope?
Nothing — the release paths are idempotent: empty slots drop nothing, and
the next resolution re-constructs.
Why is pre_destruct non-raising while post_construct may raise?
Construction happens in a raising context (resolve), so a failed
post_construct propagates and nothing is cached. Release happens inside
close() / close_scope(), which return None — there is no caller that
could handle the error, so the contract forbids it.
Is there an onClose registration API (a teardown callback table)?
No — and deliberately so. mjdi's lifecycle is type-declared (conform
to the trait) and compile-time-routed (the comptime if conforms_to(...) gates specialize every provider descriptor), not a
runtime callback registry. See
Ownership and memory for the ownership model
this rests on.