mjdi docsv0.10.0latest
Container guard (P1-14): with_container and ContainerGuard
The container sibling of the scope guard: a safe
Source: mjdi/docs/container-guard.md
The container sibling of the scope guard: a safe
pattern that makes Container.close() difficult to forget.
with_container — the function-style guard
from mjdi import with_container
def app_body(mut app: Container[type_of(reg)]) raises -> String:
app.set_value[AppConfig](AppConfig("prod"))
var service = app.resolve[UserService]()
return service.report()
var result = with_container(app, app_body)
close() is guaranteed on normal completion and on every error path —
an error raised by the body is re-raised after the container closed, so
cached canonical instances (singletons, cached factory products, cached
alias sources) and their pre_destruct hooks are always released by the
statement. The body is a thin function taking the container by mutable
reference and returning a Movable result, which with_container
forwards.
ContainerGuard — the ownership guard
var guard = ContainerGuard(app^) # move a configured container in
var service = guard.resolve[UserService]()
var session = guard.create_scope().resolve[Session]() # guards delegate scopes
var result = guard.with_scope(handle_request) # guard-level with_scope
guard.close() # exactly-once close
ContainerGuardowns the container;resolve,set_value,has_value, andcreate_scopedelegate to it, plus a guard-levelwith_scope.close()is idempotent;__deinit__closes the container if you never called it — including during error unwinding (verified bytests/test_guards.mojo).- No double destruction: the exactly-once flag is shared between
close()and the destructor. - Not
Movableon purpose (same rationale asScopeGuard).
The "resolution after closure" question
Container.close() is a non-terminal release: it drops cached
canonical instances and keeps value slots; the next resolution
re-constructs. There is therefore no "resolution after closure" error
to guard against at runtime — and the ownership guards make the related
mistake (using a container whose guard has closed it) a compile-time
impossibility, because the guard owns the container: once the guard is
gone, the container is gone with it.
Related
- Scope guard — the scope sibling.
- Lifecycle hooks — what
close()releases and whenpre_destructfires. - Construction ordering — release ordering.