mjdi

Search documentation

Search the mjdi v0.10.0 documentation

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
  • ContainerGuard owns the container; resolve, set_value, has_value, and create_scope delegate to it, plus a guard-level with_scope.
  • close() is idempotent; __deinit__ closes the container if you never called it — including during error unwinding (verified by tests/test_guards.mojo).
  • No double destruction: the exactly-once flag is shared between close() and the destructor.
  • Not Movable on purpose (same rationale as ScopeGuard).

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.