dependency_box
A 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 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}';
}
void main() {
final dbox = DependencyBox.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
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 & Shared Bindings
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:
final appBox = DependencyBox.main(name: 'app_root');
appBox.addSingleton(GlobalConfig());
// Create an isolated feature scope
final featureBox = appBox.createChild(name: 'checkout_feature');
featureBox.addSingleton(CheckoutState());
// Register a shared singleton anchored to root from within the child scope
featureBox.addSharedSingleton(SharedAnalyticsSession());
// Dispose scope and clean up scoped dependencies
featureBox.dispose();
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(),
);
โก 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 15.66รโ21.71ร faster dependency resolution thanget_it 9.3.0(e.g. Singleton: 12.96 ns vs 281.45 ns/op). - Container Setup: 3.89รโ4.35ร faster initialization and dependency binding setup.
- Production Architectures: 3.77รโ18.83ร faster across simulated real-world application lifecycles (routing, mixed traffic, startup), with specialized weak-reference caching reaching 63.72ร.
- Verified Suite Advantage: 5.56ร geometric-mean speedup in JIT and 7.10ร in AOT across comprehensive multi-workload benchmarking.
๐ฌ 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:
benchmark/dart run 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 inbenchmark/.
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.
Libraries
- dependency_box
- A high-performance, lightweight, and zero-dependency inversion-of-control (IoC) container and dependency injection box for Dart and Flutter.