# Full Guide to CherryPick DI for Dart and Flutter: Dependency Injection with Annotations and Automatic Code Generation
**CherryPick** is a powerful tool for dependency injection in Dart and Flutter projects. It offers a modern approach with code generation, async providers, named and parameterized bindings, and field injection using annotations.
> Tools:
> - [`cherrypick`](https://pub.dev/packages/cherrypick) — runtime DI core
> - [`cherrypick_annotations`](https://pub.dev/packages/cherrypick_annotations) — DI annotations
> - [`cherrypick_generator`](https://pub.dev/packages/cherrypick_generator) — DI code generation
>
---
## CherryPick advantages vs other DI frameworks
- 📦 Simple declarative API for registering and resolving dependencies
- ⚡️ Full support for both sync and async registrations
- 🧩 DI via annotations with codegen, including advanced field injection
- 🏷️ Named bindings for multiple interface implementations
- 🏭 Parameterized bindings for runtime factories (e.g., by ID)
- 🌲 Flexible scope system for dependency isolation and hierarchy
- 🕹️ Optional resolution (`tryResolve`)
- 🐞 Clear compile-time errors for invalid annotation or DI configuration
> ⚠️ **Important note about using toInstance in Module**
>
> If you register a chain of dependencies via `toInstance` inside the `builder` method of your `Module`, you must NOT call `scope.resolve<T>()` for a type that you have just bound—at this moment.
>
> CherryPick initializes all bindings inside `builder` sequentially: at the time of a new binding, not all other dependencies are registered yet in the DI container. If you try to use `scope.resolve<T>()` for an object you have just added in the same `builder`, it will result in an error (`Can't resolve dependency ...`).
>
> **Correct way:**
> Manually construct the entire object chain before registering:
>
> ```dart
> void builder(Scope scope) {
> final a = A();
> final b = B(a);
> final c = C(b);
> bind<A>().toInstance(a);
> bind<B>().toInstance(b);
> bind<C>().toInstance(c);
> }
> ```
>
> **Incorrect:**
> ```dart
> void builder(Scope scope) {
> bind<A>().toInstance(A());
> // Error! At this point, A is not registered yet.
> bind<B>().toInstance(B(scope.resolve<A>()));
> }
> ```
>
> **Incorrect:**
> ```dart
> void builder(Scope scope) {
> bind<A>().toProvide(() => A());
> // Error! At this point, A is not registered yet.
> bind<B>().toInstance(B(scope.resolve<A>()));
> }
> ```
>
> **Note:** This limitation applies only to `toInstance`. For providers (`toProvide`/`toProvideAsync`) and other strategies, you can freely use `scope.resolve<T>()` inside `builder`.
> ℹ️ **Note about `.singleton()` and `.toInstance()`:**
>
> Calling `.singleton()` after `.toInstance()` does **not** change the binding’s behavior: the object passed with `toInstance()` is already a single, constant instance that will be always returned for every resolve.
>
> It is not necessary to use `.singleton()` with an existing object—this call has no effect.
>
> `.singleton()` is only meaningful with providers (such as `toProvide`/`toProvideAsync`), to ensure only one instance is created by the factory.
> ⚠️ **Special note on using `.singleton()` after `toProvideWithParams` or `toProvideAsyncWithParams`:**
>
> If you declare a binding using `.toProvideWithParams((params) => ...)` (or its async variant) and then call `.singleton()`, the DI container will create and cache **only one instance** on the first `resolve` call—with the initial parameters. All subsequent calls to `resolve<T>(params: ...)` will return that same (cached) instance, **regardless of the new parameters**.
> final a = scope.resolve<Service>(params: 1); // Creates Service(1)
> final b = scope.resolve<Service>(params: 2); // Returns Service(1)
> print(identical(a, b)); // true
> ```
>
> In other words:
> - The provider function receives parameters only on its first call,
> - After that, no matter what parameters are passed, the same instance is always returned.
>
> **Recommendation:**
> Use `.singleton()` with parameterized providers only if you are sure all parameters should always be identical, or you intentionally want a “master” instance. Otherwise, omit `.singleton()` to ensure a new object is constructed for every unique `params` value.
For most business cases, a single root scope is enough, but CherryPick supports nested scopes:
```dart
final rootScope = CherryPick.openRootScope();
final profileScope = rootScope.openSubScope('profile')
..installModules([ProfileModule()]);
```
- **Subscope** can override parent dependencies.
- When resolving, first checks its own scope, then up the hierarchy.
## Managing names and scope hierarchy (subscopes) in CherryPick
CherryPick supports nested scopes, each can be "root" or a child. For accessing/managing the hierarchy, CherryPick uses scope names (strings) as well as convenient open/close methods.
### Open subScope by name
CherryPick uses separator-delimited strings to search and build scope trees, for example:
```dart
final subScope = CherryPick.openScope(scopeName: 'profile.settings');
```
- Here, `'profile.settings'` will open 'profile' subscope in root, then 'settings' subscope in 'profile'.
- Default separator is a dot (`.`), can be changed via `separator` argument.
**Example with another separator:**
```dart
final subScope = CherryPick.openScope(
scopeName: 'project>>dev>>api',
separator: '>>',
);
```
### Hierarchy & access
Each hierarchy level is a separate scope.
This is convenient for restricting/localizing dependencies, for example:
-`main.profile` — dependencies only for user profile
> **Starting from version 3.0.0**, CherryPick uses a Map-based resolver index for dependency lookup. This means calls to `resolve<T>()`, `tryResolve<T>()` and similar methods are now O(1) operations, regardless of the number of modules or bindings within your scope. Previously it would iterate over all modules and bindings, which could reduce performance as your project grew. This optimization is internal and does not affect the public API or usage patterns, but significantly improves resolution speed for larger applications.
## Automatic resource management: Disposable and dispose
CherryPick makes it easy to clean up resources for your singleton services and other objects registered in DI.
If your class implements the `Disposable` interface, always **await**`scope.dispose()` (or `CherryPick.closeRootScope()`) when you want to free all resources in your scope — CherryPick will automatically await `dispose()` for every object that implements `Disposable` and was resolved via DI.
This ensures safe and graceful resource management (including any async resource cleanup: streams, DB connections, sockets, etc.).
### Example
```dart
class LoggingService implements Disposable {
@override
FutureOr<void> dispose() async {
// Close files, streams, and perform async cleanup here.
final config = await scope.resolveAsync<RemoteConfig>();
```
---
## Validation and diagnostics
- If you use incorrect annotations or DI config, you'll get clear compile-time errors.
- Binding errors are found during code generation, minimizing runtime issues and speeding up development.
---
## Flutter integration: cherrypick_flutter
### What it is
[`cherrypick_flutter`](https://pub.dev/packages/cherrypick_flutter) is the integration package for CherryPick DI in Flutter. It provides a convenient `CherryPickProvider` widget which sits in your widget tree and gives access to the root DI scope (and subscopes) from context.
You can use CherryPick in Dart CLI, server apps, and microservices. All major features work without Flutter.
---
## CherryPick Example Project: Step by Step
1. Add dependencies:
```yaml
dependencies:
cherrypick: ^1.0.0
cherrypick_annotations: ^1.0.0
dev_dependencies:
build_runner: ^2.0.0
cherrypick_generator: ^1.0.0
```
2. Describe your modules using annotations.
3. To generate DI code:
```shell
dart run build_runner build --delete-conflicting-outputs
```
4. Enjoy modern DI with no boilerplate!
---
## Conclusion
**CherryPick** is a modern DI solution for Dart and Flutter, combining a concise API and advanced annotation/codegen features. Scopes, parameterized providers, named bindings, and field-injection make it great for both small and large-scale projects.
Yes! Even if none of your services currently implement `Disposable`, always use `await` when closing scopes. If you later add resource cleanup (by implementing `dispose()`), CherryPick will handle it automatically without you needing to change your scope cleanup code. This ensures resource management is future-proof, robust, and covers all application scenarios.