dependency_box 1.0.1
dependency_box: ^1.0.1 copied to clipboard
A high-performance, lightweight, and zero-dependency inversion-of-control (IoC) container and dependency injection box for Dart and Flutter
dependency_box #
A high-performance, lightweight, zero-dependency Inversion-of-Control (IoC) container and service locator for Dart and Flutter applications.
Engineered with a zero-allocation unkeyed lookup path, dependency_box achieves sub-15ns resolution latency while offering hierarchical child scopes, lock-free async initialization deduplication, circular dependency detection, and deterministic lifecycle management.
โจ Features #
- ๐ฏ Zero-Boilerplate Type Inference: Inferred registrations and resolutions without typing
<Type>angle brackets. - ๐ชถ Zero Runtime Dependencies: Pure Dart code compatible with Flutter, VM, Web, and WebAssembly (WASM).
- โก Sub-15ns Resolution: Over 75 Million ops/sec on the hot path via direct
Typeliteral map keys. - โณ 6 Registration Lifetimes: Eager singletons, lazy singletons, weak-reference caches, transient factories, parameterized factories, and async singletons.
- ๐ณ Hierarchical Child Scopes: Isolated sub-containers (
createChild()) that inherit parent registrations. - ๐ Root-Anchored Shared Singletons: Register singletons from child scopes (
addShared*) anchored directly to root. - ๐ Async Concurrency & Cycle Detection: In-flight
Futurededuplication with automatic reentrancy/circular dependency protection. - ๐งน Automatic Resource Disposal: Clean lifecycle cleanup via
DependencyDisposableand inlineonDisposehooks.
๐ฆ Getting Started #
Add dependency_box to your pubspec.yaml:
dart pub add dependency_box
or for Flutter
flutter pub add dependency_box
Import the package:
import 'package:dependency_box/dependency_box.dart';
๐ Quick Start: Zero <Type> Boilerplate #
Unlike traditional service locators where you repeat class names in angle brackets (<Config>, <Client>, <Repository>), dependency_box leverages bidirectional type inference to deduce types automatically from instances, closures, and variable declarations:
import 'package:dependency_box/dependency_box.dart';
class ApiConfig {
const ApiConfig(this.baseUrl);
final String baseUrl;
}
class ApiClient {
ApiClient(this.config);
final ApiConfig config;
}
class UserRepository {
UserRepository(this.client);
final ApiClient client;
String getUser(String id) => 'User $id from ${client.config.baseUrl}';
}
// Root Container (creates the primary container instance)
final dbox = DependencyBox.main();
void main() {
// 1. Inferred Registrations: No <Type> brackets needed!
dbox.addSingleton(const ApiConfig('https://api.example.com'));
dbox.addLazySingleton((dbox) => ApiClient(dbox.get()));
dbox.addFactory((dbox) => UserRepository(dbox.get()));
// 2. Inferred Resolution: Inferred from the variable type
final UserRepository userRepo = dbox.get();
print(userRepo.getUser('42')); // User 42 from https://api.example.com
}
๐ก Core Usage & Lifetimes #
1. Registration Lifetimes #
// Root Container (creates the primary container instance)
final dbox = DependencyBox.main();
// Eager Singleton (instantiated immediately)
dbox.addSingleton(DatabaseService());
// Lazy Singleton (instantiated once upon first get())
dbox.addLazySingleton((dbox) => AuthService(dbox.get()));
// Weak-Reference Cached Factory (cached while referenced in memory, auto-collected when unreferenced)
dbox.addCachedFactory((dbox) => HeavyImageCache());
// Transient Factory (creates a fresh instance every time get() is called)
dbox.addFactory((dbox) => OrderController(dbox.get()));
// Parameterized Factory (accepts runtime arguments)
dbox.addFactoryWith<QueryEngine, String>((dbox, query) => QueryEngine(query));
// Asynchronous Singleton (deduplicated Future resolution)
dbox.addAsyncSingleton((dbox) async {
final session = await loadRemoteSession();
return session;
});
2. Hierarchical Child Scopes & Scoping Properties #
Child scopes inherit dependencies from their parent while keeping local registrations isolated. When the child scope is disposed, its local resources are cleaned up without affecting the parent:
// Root Container (creates the primary container instance)
final appBox = DependencyBox.main(name: 'app_root');
// Eager Singleton on root
appBox.addSingleton(GlobalConfig());
// Create an isolated child scope (via convenience method)
final featureBox = appBox.createChild(name: 'checkout_feature');
// Or create a child container (via explicit parent constructor)
final childBox = DependencyBox.child(parent: appBox, name: 'child_scope');
// Scoped Singleton (isolated to child scope)
featureBox.addSingleton(CheckoutState());
// Shared Singleton (anchored to root from within the child scope)
featureBox.addSharedSingleton(SharedAnalyticsSession());
// Scope hierarchy inspection:
print(featureBox.name); // 'checkout_feature'
print(featureBox.parent); // appBox
print(featureBox.root); // appBox (topmost root across any nesting depth)
// Dispose scope and clean up scoped dependencies
featureBox.dispose();
createChild({String? name}): Importance: Creates an isolated sub-container (e.g. for user sessions, HTTP requests, or navigation flows) that inherits parent dependencies. When the child scope is disposed, its scoped resources are torn down without affecting the parent.name: Importance: An optional human-readable identifier displayed in logs, error traces, and diagnostic inspection (printContainer()) to distinguish scopes.parent: Importance: Gives direct access to the immediate parent container (ornullif root), enabling scope boundary inspection.root: Importance: Resolves the topmost root container across any nesting depth, ensuring direct access to global application singletons from deeply nested scopes.
3. Lifecycle Cleanup with DependencyDisposable #
Classes implementing DependencyDisposable or registered with custom onDispose hooks are automatically closed when their container is disposed:
class DatabaseClient implements DependencyDisposable {
@override
void dispose() {
print('Database connection closed cleanly.');
}
}
// Automatically called when dbox.dispose() is executed
dbox.addSingleton(DatabaseClient());
// Or with an inline hook for third-party classes:
dbox.addSingleton(
StreamController<String>.broadcast(),
onDispose: (controller) => controller.close(),
);
DependencyDisposable: Importance: Standard lifecycle contract (FutureOr<void> dispose()). When a container is disposed or a dependency is removed,DependencyBoxautomatically invokesdispose()on any active registered instance implementing this interface.
4. Modular Feature Registration (install & installAll) #
Package related registrations into cohesive modules implementing DependencyModule:
class NetworkModule implements DependencyModule {
@override
void register(DependencyBox box) {
box.addSingleton(HttpClient());
box.addLazySingleton((b) => ApiService(b.get()));
}
}
class AuthModule implements DependencyModule {
@override
void register(DependencyBox box) {
box.addSingleton(AuthTokenStorage());
}
}
// Root Container (creates the primary container instance)
final box = DependencyBox.main();
// Install a single module:
box.install(NetworkModule());
// Or batch-install multiple modules at the composition root:
box.installAll([NetworkModule(), AuthModule()]);
DependencyModule: Importance: Modular feature registration contract (void register(DependencyBox box)). Encapsulates related dependencies into cohesive, reusable architectural units.install(module): Importance: Enables modular, decoupled architecture by organizing feature dependencies into dedicated classes rather than maintaining a monolithic composition root.installAll(modules): Importance: Streamlines application startup sequences by cleanly registering multiple feature modules in a single call.
5. Multi-Registrations (allowMulti & allowMultiple) #
By default, duplicate registrations throw an assertion to catch accidental overwrites. When multiple implementations of a type are intentionally needed (e.g. plugins, interceptors, middleware), enable multi-registration:
abstract interface class Interceptor {
void intercept(String request);
}
// Root Container (creates the primary container instance)
final box = DependencyBox.main();
// 1. Enable multiple registrations for a type with a resolution strategy
box.allowMulti<Interceptor>(resolution: MultiResolution.last);
// Register multiple implementations of the same type
box.addSingleton<Interceptor>(AuthInterceptor());
box.addSingleton<Interceptor>(LoggingInterceptor());
// 2. Resolve all instances or the default instance
final List<Interceptor> all = box.getAll<Interceptor>().toList();
final Interceptor active = box.get(); // Resolves LoggingInterceptor (last)
// 3. Or batch-configure multiple types at once:
box.allowMultiple({
const MultiRegistration<Interceptor>.last(),
const MultiRegistration<Validator>(),
});
allowMulti<T>({resolution}): Importance: Safely opts typeTinto multiple registrations and defines howget<T>()resolves (first,last,at(index),key(key)), whilegetAll<T>()retrieves the full collection of instances.allowMultiple(types): Importance: Declaratively configures multi-registration for multiple types in a single call using compile-timeMultiRegistrationdescriptors.
โก Performance #
dependency_box is engineered around a zero-allocation unkeyed lookup path using direct Type literal map keys without wrapper objects or reflection layers.
Verified Benchmark Comparison: dependency_box vs. get_it 9.3.0 #
- Head-to-Head Resolution:
dependency_boxdelivers up to 27.71ร faster dependency resolution thanget_it 9.3.0(e.g. Singleton: 13 ns vs 362 ns in AOT; 15 ns vs 239 ns in JIT). - Container Setup: 2.30รโ6.35ร faster initialization and dependency binding setup.
- Complex Architectures: 13.87รโ19.74ร faster across deep dependency graphs and application lifecycles, with weak-reference caching reaching 27.32ร.
- Verified Suite Advantage: 5.57ร geometric-mean speedup in JIT and 6.67ร in AOT across comprehensive multi-workload benchmarking.
1. JIT Resolution Workloads
[JIT Resolution Workloads]
2. JIT Registration & Scaling
[JIT Registration & Scaling]
3. AOT Resolution Workloads
[AOT Resolution Workloads]
4. AOT Registration & Scaling
[AOT Registration & Scaling]
Tip
A consolidated 4-in-1 chart is also available at doc/benchmark_comparison.svg, along with suite overviews for JIT and AOT.
๐ฌ Reproducing the Benchmarks #
All benchmark suites and measurement harnesses are 100% open source and reproducible:
-
Comparative Benchmark Suite:
tool/comparison_benchmark/# Run head-to-head microbenchmarks (dependency_box vs get_it 9.3.0) dart run tool/comparison_benchmark/bin/compare_benchmark.dart # Run real-world production architecture simulation suite dart run tool/comparison_benchmark/bin/real_world_benchmark.dart -
Standalone Package Microbenchmarks:
tool/benchmark/dart run tool/benchmark/benchmark.dart
Note
- Benchmarks were run on Dart SDK 3.13.4 on Windows x64.
- Comparison harness sources are located in
tool/comparison_benchmark/and internal benchmarks intool/benchmark/.
Supporting & Contributing #
If you find dependency_box helpful, here are several ways you can support the project:
๐ Community Support #
- Star the Repository: Star ahmedm-gh/dart-packages on GitHub to help others discover it.
- Report Issues & Ideas: Found a bug or need an improvement? Open an issue on GitHub Issues.
- Contribute: Pull requests for optimizations, documentation, or examples are always welcome.
- Spread the Word: Recommend
dependency_boxin your Flutter/Dart teams, blogs, or communities.
โ Sponsorship & Backing #
- Sponsor on GitHub: If this package brings value to your commercial apps, consider supporting its maintenance via GitHub Sponsors.
- Buy Me a Coffee: Support development with a one-time coffee or recurring donation via Buy Me a Coffee.
Author & Maintainer #
Created and maintained by AHMED M.
- GitHub: @ahmedm-gh
- Repository: ahmedm-gh/dart-packages
License #
This package is licensed under the MIT License.