Learn

Retained local scopes

Keep feature state between visits with explicit leases, capacity, expiry and final close.

v1.3.1Intermediateark_di

Use a scope cache when a user leaves a feature and returns frequently, and recreating that feature's live state is undesirable. This is explicit lifetime management, not disk persistence or a replacement for business-data freshness.

Ownership

Create parent.createScopeCache(policy: ...) at the composition owner. Supply both maxScopes and idleTimeout; no universal retention defaults are chosen. The parent owns the cache; the cache owns real child containers. No feature registrations are added to the global/root resolver.

A stable DiScopeDefinition<A> supplies synchronous configure and an exact expose allowlist. Create the definition once, not on every widget build. A cache entry is identified by definition identity plus immutable typed arguments with correct equality/hash codes. debugLabel is diagnostic only. Changed account, tenant or other significant context must not accidentally reuse the same key. For logout, close the session cache/parent rather than relying on TTL.

The modular cart example is a complete runnable program showing configuration, acquire, mutation, release, synchronous reuse and final application close.

Access is not ownership

await cache.acquire(definition, arguments: key) returns one DiScopeLease. Each concurrent consumer has a separate lease even when the graph is shared. tryAcquire returns a ready lease synchronously or null; it does not create a graph. Concurrent first acquisitions share configuration, not their lease.

Use lease.resolver and call await lease.release() when done. Release revokes that resolver immediately, including saved references to it. It does not revoke other consumers. whenEnded signals access ending, not physical disposal. Already returned dependency objects cannot be revoked by DI; stop using them when access ends. Forgotten leases are not automatically released by GC.

Existing managed instances and their current state survive idle retention. Transient factories remain transient. Already accepted async singleton work can finish and be shared on reacquisition; arbitrary business futures are neither tracked nor cancelled just because the DI container is cached.

Keep removed widgets out of retained state

Use lease.createChild(viewDefinition, arguments: ...) for screen-bound objects. The resulting DiOwnedScope is not cached. Its resolver is restricted too. Close it before releasing the feature lease. A child independently pins the feature until its cleanup/rollback finishes. Closing an owned subtree revokes all of its nested resolvers before asynchronous disposal begins.

Do not retain BuildContext, State, tickers or widget-bound controllers in the cached feature. A presenter belongs in the retained or per-view graph according to its actual lifecycle contract, not simply its class name.

Idle retention and final close

  • The idle timeout starts after the last consumer/view pin leaves.
  • Reacquisition cancels the old idle deadline. The next idle period starts anew.
  • At capacity, the oldest idle graph is retired; active users are protected.
  • Creating and retiring graphs still occupy capacity. A victim's replacement cannot create its graph before cleanup finishes.
  • When all slots are in use/reserved/retiring, a new key receives DiScopeCacheCapacityException; there is no hidden unbounded queue.
  • Zero timeout closes after the last consumer instead of retaining idle state.

trimIdle() removes unused graphs and joins retirement already underway. invalidate/invalidateAll immediately revoke the selected generations and await cleanup, including active ones. The cache remains usable for new generations. close() permanently rejects new acquisitions and awaits accepted creation/rollback/retirement. Closing the parent also closes the cache before parent-owned resources. Late releases never affect a replacement generation.

Close is idempotent. All disposers are attempted; explicit cleanup reports DiCloseException. Background TTL cleanup reports to onEvictionError, or the captured owner zone. Async reporter failures are observed separately. A failed disposer is not proof that the external resource actually closed. No forced cancellation or timeout is imposed on user disposer futures.

TTL uses monotonic intervals and one nearest-deadline timer. A lookup checks expiry even if the callback is late. This is not a security erasure guarantee while the process/device is suspended. Idle does not automatically pause network activity or refresh data; that policy belongs to the feature.

Setup failures and restricted publication

DiContainer.build and createChild keep synchronous configuration. Failed configuration rolls back accepted container-owned bindInstance resources in reverse registration order. External/rejected resources are not disposed by DI. Lazy factories are not invoked merely to clean up a failed configuration.

buildAsync/createChildAsync await rollback before forwarding the same original error and stack. In synchronous calls, cleanup continues after the first async disposer; catching the setup error does not mean cleanup has finished. Supply onRollbackError for secondary cleanup failures; without it the captured zone receives them. Reporter IO is observed, not awaited.

DiResolverView.only(source, allowed: descriptors) copies the exact allowlist. It exposes no lifecycle API and does not widen an already restricted source. Denied getAsync calls fail through their future. Internal factory resolution still follows normal owner rules. This capability boundary is not a sandbox against arbitrary application code that already possesses other references.