Ark DI

Pure Dart dependency injection with hierarchical scopes, explicit ownership, deterministic asynchronous initialization, and dependency-ordered teardown.

Ark DI builds an object graph without requiring global variables, static service locators, generated code, reflection, or Flutter. A root container can own application-wide dependencies. Child containers provide bounded scopes, inherit missing registrations, and make test or feature overrides explicit.

Русская версия

This guide includes the retained scopes, modules, rollback and diagnostics available since 1.3. The original registration API remains compatible.

Why this package exists

Dependency injection is often reduced to a global map of factories. That makes access convenient but leaves important runtime questions unanswered:

  • Which scope owns an instance?
  • Does a factory return a transient object or cache it?
  • What happens when several callers initialize one async dependency?
  • Can a child silently replace a parent registration?
  • Which object closes first when one dependency uses another?
  • What happens to active work when a scope starts closing?

Ark DI encodes those decisions in the registration API and container lifecycle. The package remains infrastructure: it constructs, resolves, and closes dependencies, but does not decide application architecture or hide dependencies behind a global access point.

Core model

Composition root
  └── DiContainer.build
        ├── instance
        ├── transient factory
        ├── async transient factory
        ├── lazy singleton
        ├── async lazy singleton
        └── child scope
              ├── local registrations
              ├── explicit parent overrides
              └── fallback to parent registrations

The central roles are deliberately separate:

  • DiBinder configures a container once;
  • DiResolver reads dependencies while an object graph is being resolved;
  • DiContainer owns registrations, child scopes, active resolutions, and container-managed lifecycle;
  • DiKey<T> distinguishes named registrations of the same type;
  • DiDisposer<T> defines explicit synchronous or asynchronous cleanup.

Installation

Build applications with a patched stable SDK: Dart 3.13.7+ or Flutter 3.47.8+. Package SDK constraints describe API compatibility, not the security of older runtimes. After the eMudhra incident, affected applications must be rebuilt and redistributed; updating a library alone is not enough. See the SDK security guidance.

dependencies:
  ark_di: ^1.3.1

Import the public library:

import 'package:ark_di/ark_di.dart';

Quick start

Define dependencies through ordinary Dart constructors and interfaces:

abstract interface class UserRepository {
  Future<User> loadCurrentUser();
}

final class HttpUserRepository implements UserRepository {
  HttpUserRepository(this.client);

  final ApiClient client;

  @override
  Future<User> loadCurrentUser() => client.getCurrentUser();
}

Build the graph in one composition root:

final DiContainer application = DiContainer.build((binder) {
  binder.bindInstance<AppConfig>(
    const AppConfig(apiBaseUrl: 'https://api.example.com'),
  );

  binder.bindAsyncLazySingleton<ApiClient>(
    (resolver) async {
      final AppConfig config = resolver.get<AppConfig>();
      return ApiClient.connect(config.apiBaseUrl);
    },
    dispose: (client) => client.close(),
  );

  binder.bindAsyncLazySingleton<UserRepository>(
    (resolver) async {
      final ApiClient client = await resolver.getAsync<ApiClient>();
      return HttpUserRepository(client);
    },
  );
});

final UserRepository repository =
    await application.getAsync<UserRepository>();

await application.close();

Factories receive their dependencies through the supplied DiResolver. Application objects still receive dependencies through constructors; they do not need to know that Ark DI exists.

Registration strategies

Binder method Creation Cache Container disposal
bindInstance Before registration Supplied object Yes by default
bindFactory Every get or getAsync None No
bindAsyncFactory Every getAsync None No
bindLazySingleton First resolution One per registration owner Yes
bindAsyncLazySingleton First async resolution One per registration owner Yes

Transient factories intentionally do not accept a disposer. The container does not retain their results, so the consumer that retains a transient object also owns its lifecycle.

Inspecting registrations

Use describe<T>() to find the effective registration without creating its dependency. visibleRegistrations lists all effective registrations from the current scope and its parents; a local override hides its parent entry.

final DiRegistrationSnapshot? repository =
    featureScope.describe<UserRepository>();

if (repository != null) {
  print(repository.kind);         // e.g. asyncLazySingleton
  print(repository.ownerDepth);   // 0: local, 1: parent
  print(repository.isInitialized); // whether a cached value exists
}

Snapshots contain descriptors and status, never instances or Factory callbacks. isInitializing identifies an in-flight Lazy Singleton. The observedDependencies list contains only successful relationships between container-owned registrations in the same owner scope. It grows when a Factory actually resolves a dependency; it cannot predict unexecuted branches or describe transient products. After close, the container's visible list is empty, while an earlier snapshot remains a detached value.

Choose a local scope lifetime

Need API When the objects close
A feature lives only while its owner is present createChild / createChildAsync The owner awaits child close()
Returning to a feature should preserve live state createScopeCache + acquire Idle eviction, invalidation or cache/parent close
A screen uses a retained feature but owns UI-bound objects lease.createChild The screen closes its DiOwnedScope before releasing the lease

A cached scope is still local. Its registrations do not become visible from the application root. Retention preserves managed objects and their last in-memory state; it is not disk persistence and does not decide when data is stale.

Retain state between visits

For example, keep an unsent draft while its feature is temporarily closed. Create the cache at a stable application/session owner, not on every visit. Create each definition once too: its identity and immutable arguments form the key.

This complete program opens a draft, releases access, reopens the same draft, and finally closes the owning application:

import 'package:ark_di/ark_di.dart';

Future<void> main() async {
  final DiContainer application = DiContainer.build((final DiBinder binder) {});
  final DiScopeCache cache = application.createScopeCache(
    policy: const DiScopeCachePolicy(
      maxScopes: 2,
      idleTimeout: Duration(minutes: 5),
    ),
  );
  final DiScopeDefinition<String> drafts = DiScopeDefinition<String>(
    configure: (final DiBinder binder, final String documentId) {
      binder.bindLazySingleton<_Draft>((final DiResolver resolver) => _Draft());
    },
    expose: (final String documentId) => <DiDependencyDescriptor>[
      const DiDependencyDescriptor(type: _Draft),
    ],
  );

  try {
    final DiScopeLease first = await cache.acquire(drafts, arguments: 'document-7');
    try {
      first.resolver.get<_Draft>().text = 'Unsent draft';
    } finally {
      await first.release();
    }

    // The feature is idle, not global. Reopen the same definition and arguments.
    final DiScopeLease reopened =
        await cache.acquire(drafts, arguments: 'document-7');
    try {
      print(reopened.resolver.get<_Draft>().text); // Unsent draft
      print(cache.diagnostics.scopes.single.state); // DiCachedScopeState.inUse
    } finally {
      await reopened.release();
    }
  } finally {
    // Final close also closes the cache and its retained child containers.
    await application.close();
  }
}

final class _Draft {
  // Empty text is a valid initial draft, not a missing identifier.
  String text = '';
}

Each acquire returns its own DiScopeLease. Release every lease, including on failures. Release revokes that lease's resolver immediately; it does not close a graph still used by another lease. tryAcquire returns a ready lease synchronously or null, without creating a graph. Transient factories still create new objects; caching a scope does not turn a factory into a singleton.

The owner explicitly chooses maxScopes and idleTimeout:

  • TTL starts after the last lease and view child leave; reopening restarts the next idle period.
  • At capacity, the oldest idle graph is closed before another graph uses its slot. Active/reserved/retiring slots cannot be silently displaced. If no slot is available, acquisition fails with DiScopeCacheCapacityException.
  • trimIdle() closes unused graphs. invalidate / invalidateAll also revoke active generations; the cache can subsequently create replacements.
  • cache.close() is final. Parent close() also closes its caches. For logout/account changes close or invalidate the relevant session scopes; TTL alone is not an account-isolation policy.

Do not put BuildContext, widget State, tickers or screen-owned controllers in retained state. Use an owned view child and close it first. DI cannot revoke an object already returned to application code or automatically release a forgotten lease through garbage collection.

See the retained-scope guide for exact ownership, expiry, cleanup errors and asynchronous setup boundaries. The modular cart example also demonstrates modules, synchronous reuse and final close.

Compose modules without a global registry

Implement DiModule.configure(DiBinder) for each group of registrations. DiConfiguration(<DiModule>[...]) copies the module list and applies it in declaration order. Pass configuration.configure to the existing container or child creation method. All modules use the same transaction; duplicate registrations still fail and parent overrides remain explicit.

Modules are reusable registration recipes, not containers of shared live resources. Do not give two independent roots ownership of one captured client.

Failed setup and restricted access

If configuration throws, accepted container-owned instances are rolled back in reverse registration order. External/rejected instances are not disposed. Use buildAsync / createChildAsync when the caller must await rollback before receiving the original setup error. Synchronous creation preserves its error but asynchronous cleanup may still be running. onRollbackError reports secondary cleanup failures separately.

DiResolverView.only(source, allowed: descriptors) provides resolution of an exact copied allowlist without exposing container lifecycle/configuration. Cached leases and owned view children publish restricted resolvers too. This is an application capability boundary, not a sandbox for arbitrary code that already holds other references.

Observe activity without creating dependencies

container.diagnostics returns a detached DiContainerSnapshot; cache.diagnostics returns a detached DiScopeCacheSnapshot. Reading them does not initialize lazy dependencies. Inspect async resolution activity, singleton initialization, cache occupancy, leases/view pins and close progress. They do not expose live business instances or cache arguments.

container.diagnostics.closeProgress identifies the close phase and attempted cleanup counts. A snapshot does not update itself: read another to observe progress. Counters are not memory measurements or a predicted completion percentage.

The composition and diagnostics guide explains the counters and cleanup phases. Isolated fixtures and matchers live in the separate ark_di_test development dependency.

Instance ownership

An already created instance belongs to the container by default:

binder.bindInstance<Database>(
  database,
  dispose: (instance) => instance.close(),
);

Container ownership means that the container retains the registration until close and releases it in the correct teardown order. A disposer is optional. When it is null, closing simply releases the container's reference.

Use external ownership only when another scope is responsible for the object:

binder.bindInstance<PlatformChannel>(
  sharedChannel,
  ownership: DiOwnership.external,
);

An externally owned instance cannot declare a container disposer. This avoids two owners attempting to close the same resource.

Factory resolution context

Factories must use the resolver supplied to them:

binder.bindLazySingleton<CatalogService>(
  (resolver) => CatalogService(
    repository: resolver.get<CatalogRepository>(),
  ),
);

Do not capture a container and turn it into a hidden service locator. Do not retain the factory resolver for later use. It expires after the root resolution and all nested asynchronous work finish. Reusing it then throws DiResolutionContextExpiredException and it no longer retains the container.

Asynchronous dependencies

Async factories and async lazy singletons always require getAsync<T>():

final Session session = await container.getAsync<Session>();

get<T>() rejects an async registration even after an async singleton has initialized. This keeps call-site behavior deterministic and independent of earlier execution order.

Concurrent requests for an async lazy singleton share one in-flight factory:

final Future<ApiClient> first = container.getAsync<ApiClient>();
final Future<ApiClient> second = container.getAsync<ApiClient>();

Both futures resolve to the same cached instance. If initialization fails, the failure is delivered to every waiting caller, the failed value is not cached, and a later request may retry.

Named registrations

Use DiKey<T> when several configurations have the same contract and type:

abstract final class ClientKeys {
  static const DiKey<ApiClient> publicApi = DiKey<ApiClient>('public-api');
  static const DiKey<ApiClient> telemetry = DiKey<ApiClient>('telemetry');
}

binder.bindInstance<ApiClient>(publicClient, key: ClientKeys.publicApi);
binder.bindInstance<ApiClient>(telemetryClient, key: ClientKeys.telemetry);

final ApiClient client = container.get<ApiClient>(key: ClientKeys.publicApi);

Prefer different interface types when dependencies have materially different responsibilities. Keys are best for multiple configurations of one genuine contract, not for hiding unrelated behavior behind strings.

Child scopes and overrides

A child resolves locally first and falls back through its parent hierarchy:

final DiContainer requestScope = application.createChild((binder) {
  binder.bindInstance<RequestContext>(requestContext);
});

Shadowing is never implicit. A child must declare the intent:

final DiContainer testScope = application.createChild((binder) {
  binder.bindInstance<UserRepository>(
    FakeUserRepository(),
    overrideParent: true,
  );
});

Setting overrideParent: true without a matching ancestor is also rejected. These two checks catch misspelled keys, missing production registrations, and accidental shadowing while the graph is configured.

A parent-owned factory resolves its own dependencies from the parent scope. It does not capture a child override merely because the request started in that child. This prevents a long-lived parent singleton from retaining scoped child state.

Test substitutions

Child scopes provide bounded test substitutions without mutating the production container:

final DiContainer testScope = production.createChild((binder) {
  binder.bindInstance<Clock>(FakeClock(), overrideParent: true);
  binder.bindInstance<UserRepository>(
    InMemoryUserRepository(),
    overrideParent: true,
  );
  binder.bindLazySingleton<UseCase>(
    (resolver) => UseCase(
      clock: resolver.get<Clock>(),
      repository: resolver.get<UserRepository>(),
    ),
    overrideParent: true,
  );
});

final UseCase useCase = testScope.get<UseCase>();

await testScope.close();
await production.close();

Register the object under test locally when it must consume local overrides. A parent singleton intentionally remains connected to its parent dependencies.

Lifecycle and teardown

close() has three guarantees:

  1. new public resolutions and child creation are rejected immediately;
  2. child scopes and active resolutions are allowed to finish;
  3. container-owned instances are disposed in dependency order.

If CatalogService resolved CatalogRepository, the service is disposed before the repository. Independent instances are disposed in reverse creation order. Synchronous and asynchronous disposers are both awaited.

Every disposer is attempted. When several fail, close() finishes teardown and throws one DiCloseException containing ordered DiCloseFailure records. The container is closed even when cleanup reports failures.

Repeated close() calls return the same future. Closing a root also closes all attached children. Closing a child independently detaches it without closing its parent.

Circular dependencies

Ark DI detects:

  • direct and indirect synchronous cycles;
  • direct and indirect asynchronous cycles;
  • cycles formed by concurrent async singleton initialization.

DiCircularDependencyException.path contains the repeated endpoint, for example CatalogService -> CatalogRepository -> CatalogService.

A cycle normally signals that responsibilities should be separated or that a runtime interaction should replace construction-time coupling.

Architectural boundaries

Ark DI is not:

  • a global or static service locator;
  • a reflection or code-generation framework;
  • a Flutter state-management package;
  • an application lifecycle singleton;
  • an automatic close() or dispose() detector;
  • a cancellation or timeout policy for arbitrary user futures.

The core package stays pure Dart. Flutter context integration belongs in the separate ark_di_flutter companion package.

Public API

API Responsibility
DiContainer Root and child scopes, resolution, ownership, close
DiBinder One-shot registration configuration
DiResolver Contextual sync and async resolution
DiKey<T> Type-safe qualifier for named registrations
DiOwnership Container or external ownership for supplied instances
DiRegistrationKind Registration strategy in diagnostics
DiContainerState Active, closing, or closed lifecycle state
DiModule / DiConfiguration Typed registration recipes in one ordered transaction
DiScopeCache / DiScopeCachePolicy Owned local state retention with explicit capacity and TTL
DiScopeDefinition<A> Stable scope recipe and public type/key allowlist
DiScopeLease / DiOwnedScope Borrowed feature access and noncached owned view children
DiResolverView Resolution-only access to an exact allowlist
DiContainerSnapshot / DiScopeCacheSnapshot Detached runtime/cache diagnostics
DiCloseProgress / DiClosePhase Observed teardown steps and attempted cleanup counts
DiException / DiFailure Original sealed failure family / open common failure contract

Documentation and project

AI agent skill

The package ships ark-di-container-configuration, a version-matched skill for registration lifetimes, ownership, scopes, async resolution, overrides, and ordered teardown.

dart run skills@ get -p ark_di

Review installed instructions before use and keep application composition rules in project-owned files.

License

Licensed under the Apache License, Version 2.0. See LICENSE and NOTICE.

Libraries

ark_di
Pure Dart dependency injection with hierarchical scopes, explicit ownership, deterministic async initialization, and ordered teardown.