Compare commits

..

26 Commits

Author SHA1 Message Date
Sergey Penkovsky
d93d4173a2 chore(release): publish packages
- cherrypick@3.0.0-dev.7
 - cherrypick_annotations@1.1.1
 - cherrypick_flutter@1.1.3-dev.7
 - cherrypick_generator@1.1.1
2025-08-11 12:38:17 +03:00
Sergey Penkovsky
85aa23d7ed Update README.md 2025-08-11 12:35:02 +03:00
Sergey Penkovsky
51cf4a0dc0 docs(readme): add comprehensive section on annotations and DI code generation
- Added 'Using Annotations & Code Generation' section explaining DI annotations flow.
- Included full table of supported annotations, practical usage examples, setup steps, troubleshooting, and references.
- Improves onboarding for CherryPick users using @injectable, @module, @provide, @named, @scope, @params and related features.

See doc/annotations_en.md and generator/module READMEs for extended docs.
2025-08-11 12:24:44 +03:00
Sergey Penkovsky
8f980ff111 docs(readme): add detailed section and examples for automatic Disposable resource cleanup\n\n- Added a dedicated section with English description and code samples on using Disposable for automatic resource management.\n- Updated Features to include automatic resource cleanup for Disposable dependencies.\n\nHelps developers understand and implement robust DI resource management practices. 2025-08-11 12:02:32 +03:00
Sergey Penkovsky
4d872d7c25 docs(disposable): add detailed English documentation and usage examples for Disposable interface; chore: update binding_resolver and add explanatory comment in scope_test for deprecated usage.\n\n- Expanded Disposable interface docs, added sync & async example classes, and CherryPick integration sample.\n- Clarified how to implement and use Disposable in DI context.\n- Updated binding_resolver for internal improvements.\n- Added ignore for deprecated member use in scope_test for clarity and future upgrades.\n\nBREAKING CHANGE: Documentation style enhancement and clearer API usage for Disposable implementations. 2025-08-11 11:53:25 +03:00
Sergey Penkovsky
450f4231cb Merge pull request #14 from pese-git/dispose
Dispose
2025-08-11 11:40:57 +03:00
Sergey Penkovsky
cd1b9cf49d fix(comment): fix warnings 2025-08-08 23:42:35 +03:00
Sergey Penkovsky
33775f5748 fix(license): correct urls 2025-08-08 23:24:05 +03:00
Sergey Penkovsky
e5848784ac refactor(core): make closeRootScope async and await dispose
BREAKING CHANGE: closeRootScope is now async (returns Future<void> and must be awaited). This change improves resource lifecycle management by allowing asynchronous cleanup when disposing the root Scope. All usages of closeRootScope should be updated to use await.

- Change closeRootScope from void to Future<void> and add async keyword
- Await _rootScopefor correct async disposal
- Ensures proper disposal and better future extensibility for async resources

Closes #xxx (replace if issue exists)
2025-08-08 16:56:37 +03:00
Sergey Penkovsky
40b3cbb422 chore(release): publish packages
- cherrypick@3.0.0-dev.6
 - cherrypick_flutter@1.1.3-dev.6
2025-08-08 16:23:13 +03:00
Sergey Penkovsky
a4b0ddfa54 docs(faq): add best practice FAQ about using await with scope disposal
- Added FAQ section in documentation (README and tutorials, EN + RU) recommending always using await when calling CherryPick.closeRootScope, scope.closeScope, or scope.dispose, even if no services implement Disposable.
- Clarifies future-proof resource management for all users.
2025-08-08 16:08:33 +03:00
Sergey Penkovsky
547a15fa4e docs(faq): add best practice FAQ about using await with scope disposal
- Added FAQ section in documentation (README and tutorials, EN + RU) recommending always using await when calling CherryPick.closeRootScope, scope.closeScope, or scope.dispose, even if no services implement Disposable.
- Clarifies future-proof resource management for all users.
2025-08-08 16:08:33 +03:00
Sergey Penkovsky
a9c95f6a89 docs+feat: add Disposable interface source and usage example
feat(core,doc): unified async dispose mechanism for resource cleanup

BREAKING CHANGE:

- Added full support for asynchronous resource cleanup via a unified FutureOr<void> dispose() method in the Disposable interface.
- The Scope now provides only Future<void> dispose() for disposing all tracked resources and child scopes (sync-only dispose() was removed).
- All calls to cleanup in code and tests (scope itself, subscopes, and custom modules) now require await ...dispose().
- Documentation and all examples updated: resource management is always async and must be awaited; Disposable implementers may use both sync and async cleanup.
- Old-style, synchronous cleanup methods have been completely removed (API is now consistently async for all DI lifecycle management).
- Example and tutorial code now demonstrate async resource disposal patterns.
2025-08-08 16:08:29 +03:00
Sergey Penkovsky
61f2268d63 fix(riverpod-adapter): update implementation in riverpod_adapter.dart 2025-08-08 15:08:27 +03:00
Sergey Penkovsky
f6fcb76730 docs(benchmark): update DI benchmark reports with new scenario tables and updated explanations 2025-08-08 15:02:45 +03:00
Sergey Penkovsky
f8bbaf6c2c Merge pull request #18 from pese-git/logger
Logger
2025-08-08 14:27:53 +03:00
Sergey Penkovsky
2ebc997fea docs(readme): add comprehensive DI state and action logging to features 2025-08-08 13:40:39 +03:00
Sergey Penkovsky
d15f3063fc hotfix 2025-08-08 12:49:12 +03:00
Sergey Penkovsky
1e8b8db64a docs(helper): add complete DartDoc with real usage examples for CherryPick class 2025-08-08 12:43:09 +03:00
Sergey Penkovsky
c3ec52823e fix: improve global cycle detector logic 2025-08-08 12:24:07 +03:00
Sergey Penkovsky
16e05d27c5 docs(log_format): add detailed English documentation for formatLogMessage function 2025-08-08 11:28:12 +03:00
Sergey Penkovsky
1131be44da feat(core): refactor root scope API, improve logger injection, helpers, and tests
- BREAKING CHANGE: introduce CherryPick.openRootScope
- add logger injection to Scope
- refactor helper and scope logic
- improve internal logging
- enhance and update tests
- add log_format.dart module
2025-08-08 11:24:03 +03:00
Sergey Penkovsky
c971b59483 feat(postly): add explicit PrintLogger setup in main.dart for debug builds 2025-08-08 08:24:19 +03:00
Sergey Penkovsky
aa97632add feat(logger): add extensible logging API, usage examples, and bilingual documentation
- Introduce CherryPickLogger interface, PrintLogger and SilentLogger implementations
- Add setGlobalLogger() to CherryPick API for custom DI logging
- Log key events (scope, module, error) via logger throughout DI lifecycle
- Comprehensive comments and code documentation in both English and Russian
- Document usage of logging system in quick_start and full_tutorial documentation (EN/RU)
- Provide usage examples in docs and code comments
- No logging inside GlobalCycleDetectionMixin (design choice: exceptions handled at Scope, not detector/mixin level) and detailed architectural reasoning
- Update helper.dart, logger.dart: comments, examples, API doc improvements
BREAKING CHANGE: Projects can now inject any logger via CherryPick.setGlobalLogger; default log behavior clarified and docstrings/usage examples enhanced
2025-08-08 08:24:13 +03:00
Sergey Penkovsky
41d49e98d0 docs(report): update comparative DI benchmark results and conclusions for cherrypick, get_it, riverpod (eng, ru) 2025-08-07 16:46:53 +03:00
Sergey Penkovsky
44a8a3fcb2 chore(pubspec): update pubspec and lock files for all packages, version bump and deps sync 2025-08-07 16:28:47 +03:00
77 changed files with 2036 additions and 493 deletions

View File

@@ -3,6 +3,81 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## 2025-08-11
### Changes
---
Packages with breaking changes:
- [`cherrypick` - `v3.0.0-dev.7`](#cherrypick---v300-dev7)
Packages with other changes:
- [`cherrypick_annotations` - `v1.1.1`](#cherrypick_annotations---v111)
- [`cherrypick_flutter` - `v1.1.3-dev.7`](#cherrypick_flutter---v113-dev7)
- [`cherrypick_generator` - `v1.1.1`](#cherrypick_generator---v111)
---
#### `cherrypick` - `v3.0.0-dev.7`
- **FIX**(comment): fix warnings.
- **FIX**(license): correct urls.
- **FEAT**: add Disposable interface source and usage example.
- **DOCS**(readme): add comprehensive section on annotations and DI code generation.
- **DOCS**(readme): add detailed section and examples for automatic Disposable resource cleanup\n\n- Added a dedicated section with English description and code samples on using Disposable for automatic resource management.\n- Updated Features to include automatic resource cleanup for Disposable dependencies.\n\nHelps developers understand and implement robust DI resource management practices.
- **DOCS**(faq): add best practice FAQ about using await with scope disposal.
- **DOCS**(faq): add best practice FAQ about using await with scope disposal.
- **BREAKING** **REFACTOR**(core): make closeRootScope async and await dispose.
- **BREAKING** **DOCS**(disposable): add detailed English documentation and usage examples for Disposable interface; chore: update binding_resolver and add explanatory comment in scope_test for deprecated usage.\n\n- Expanded Disposable interface docs, added sync & async example classes, and CherryPick integration sample.\n- Clarified how to implement and use Disposable in DI context.\n- Updated binding_resolver for internal improvements.\n- Added ignore for deprecated member use in scope_test for clarity and future upgrades.\n\nBREAKING CHANGE: Documentation style enhancement and clearer API usage for Disposable implementations.
#### `cherrypick_annotations` - `v1.1.1`
- **FIX**(license): correct urls.
#### `cherrypick_flutter` - `v1.1.3-dev.7`
- **FIX**(license): correct urls.
#### `cherrypick_generator` - `v1.1.1`
- **FIX**(license): correct urls.
## 2025-08-08
### Changes
---
Packages with breaking changes:
- [`cherrypick` - `v3.0.0-dev.6`](#cherrypick---v300-dev6)
Packages with other changes:
- [`cherrypick_flutter` - `v1.1.3-dev.6`](#cherrypick_flutter---v113-dev6)
Packages with dependency updates only:
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
- `cherrypick_flutter` - `v1.1.3-dev.6`
---
#### `cherrypick` - `v3.0.0-dev.6`
- **FIX**: improve global cycle detector logic.
- **DOCS**(readme): add comprehensive DI state and action logging to features.
- **DOCS**(helper): add complete DartDoc with real usage examples for CherryPick class.
- **DOCS**(log_format): add detailed English documentation for formatLogMessage function.
- **BREAKING** **FEAT**(core): refactor root scope API, improve logger injection, helpers, and tests.
- **BREAKING** **FEAT**(logger): add extensible logging API, usage examples, and bilingual documentation.
## 2025-08-07
### Changes

View File

@@ -192,7 +192,7 @@
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,

View File

@@ -1,79 +1,51 @@
# DI Benchmark Results: cherrypick vs get_it
# Comparative DI Benchmark Report: cherrypick vs get_it vs riverpod
## Benchmark parameters
## Benchmark Scenarios
| Parameter | Value |
|------------------|-----------------------|
| --benchmark | all |
| --chainCount (-c)| 10, 100 |
| --nestingDepth (-d)| 10, 100 |
| --repeat (-r) | 2 |
| --warmup (-w) | 1 (default) |
| --format (-f) | markdown |
| --di | cherrypick, get_it |
1. **RegisterSingleton** — Registers and resolves a singleton. Baseline DI speed.
2. **ChainSingleton** — A dependency chain A → B → ... → N (singleton). Deep singleton chain resolution.
3. **ChainFactory** — All chain elements are factories. Stateless creation chain.
4. **AsyncChain** — Async chain (async factory). Performance on async graphs.
5. **Named** — Registers two bindings with names, resolves by name. Named lookup test.
6. **Override** — Registers a chain/alias in a child scope. Tests scope overrides.
---
## Benchmark scenarios
## Comparative Table: chainCount=10, nestingDepth=10 (Mean, PeakRSS)
**(1) RegisterSingleton**
Registers and resolves a singleton. Baseline DI speed.
| Scenario | cherrypick Mean (us) | cherrypick PeakRSS | get_it Mean (us) | get_it PeakRSS | riverpod Mean (us) | riverpod PeakRSS |
|--------------------|---------------------:|-------------------:|-----------------:|---------------:|-------------------:|-----------------:|
| RegisterSingleton | 13.00 | 273104 | 8.40 | 261872 | 9.80 | 268512 |
| ChainSingleton | 13.80 | 271072 | 2.00 | 262000 | 33.60 | 268784 |
| ChainFactory | 5.00 | 299216 | 4.00 | 297136 | 22.80 | 271296 |
| AsyncChain | 28.60 | 290640 | 24.60 | 342976 | 78.20 | 285920 |
| Named | 2.20 | 297008 | 0.20 | 449824 | 6.20 | 281136 |
| Override | 7.00 | 297024 | 0.00 | 449824 | 30.20 | 281152 |
**(2) ChainSingleton**
A dependency chain A → B → ... → N (singleton). Measures how fast DI resolves deep singleton chains by name.
## Maximum Load: chainCount=100, nestingDepth=100 (Mean, PeakRSS)
**(3) ChainFactory**
Same as ChainSingleton, but every chain element is a factory. Shows DI speed for stateless 'creation chain'.
**(4) AsyncChain**
Async chain (async factory). Measures DI performance for async graphs.
**(5) Named**
Registers two bindings with names ("impl1", "impl2"), resolves by name. Tests named lookup.
**(6) Override**
Registers a chain/alias in a child scope and resolves UniversalService without a name in that scope. Simulates override and modular/test architecture.
| Scenario | cherrypick Mean (us) | cherrypick PeakRSS | get_it Mean (us) | get_it PeakRSS | riverpod Mean (us) | riverpod PeakRSS |
|--------------------|---------------------:|-------------------:|-----------------:|---------------:|-------------------:|-----------------:|
| RegisterSingleton | 4.00 | 271072 | 1.00 | 262000 | 2.00 | 268688 |
| ChainSingleton | 76.60 | 303312 | 2.00 | 297136 | 221.80 | 270784 |
| ChainFactory | 80.00 | 293952 | 39.20 | 342720 | 195.80 | 308640 |
| AsyncChain | 251.40 | 297008 | 18.20 | 450640 | 748.80 | 285968 |
| Named | 2.20 | 297008 | 0.00 | 449824 | 1.00 | 281136 |
| Override | 104.80 | 301632 | 2.20 | 477344 | 120.80 | 294752 |
---
## Comparative Table (Mean, ΔRSS), chainCount=10, nestingDepth=10
## Analysis
| Scenario | cherrypick Mean (us) | cherrypick ΔRSS | get_it Mean (us) | get_it ΔRSS |
|--------------------|---------------------:|----------------:|-----------------:|------------:|
| RegisterSingleton | 21.0 | 320 | 24.5 | 80 |
| ChainSingleton | 112.5 | -3008 | 2.0 | 304 |
| ChainFactory | 8.0 | 0 | 4.0 | 0 |
| AsyncChain | 36.5 | 0 | 13.5 | 0 |
| Named | 1.5 | 0 | 0.5 | 0 |
| Override | 27.5 | 0 | 0.0 | 0 |
- **get_it** is the absolute leader in all scenarios, especially under deep/nested chains and async.
- **cherrypick** is highly competitive and much faster than riverpod on any complex graph.
- **riverpod** is only suitable for small/simple DI graphs due to major slowdowns with depth, async, or override.
## Maximum load: chainCount=100, nestingDepth=100
| Scenario | cherrypick Mean (us) | cherrypick ΔRSS | get_it Mean (us) | get_it ΔRSS |
|--------------------|---------------------:|----------------:|-----------------:|------------:|
| RegisterSingleton | 1.0 | 32 | 1.0 | 0 |
| ChainSingleton | 3884.0 | 0 | 1.5 | 34848 |
| ChainFactory | 4088.0 | 0 | 50.0 | 12528 |
| AsyncChain | 4287.0 | 0 | 17.0 | 63120 |
| Named | 1.0 | 0 | 0.0 | 0 |
| Override | 4767.5 | 0 | 1.5 | 14976 |
### Recommendations
- Use **get_it** for performance-critical and deeply nested graphs.
- Use **cherrypick** for scalable/testable apps if a small speed loss is acceptable.
- Use **riverpod** only if you rely on Flutter integration and your DI chains are simple.
---
## Scenario explanations
- **RegisterSingleton:** Registers and resolves a singleton dependency, baseline test for cold/hot startup speed.
- **ChainSingleton:** Deep chain of singleton dependencies. Cherrypick is much slower as depth increases; get_it is nearly unaffected.
- **ChainFactory:** Creation chain with new instances per resolve. get_it generally faster on large chains due to ultra-simple factory registration.
- **AsyncChain:** Async factory chain. get_it processes async resolutions much faster; cherrypick is much slower as depth increases due to async handling.
- **Named:** Both DI containers resolve named bindings nearly instantly, even on large graphs.
- **Override:** Child scope override. get_it (thanks to stack-based scopes) resolves immediately; cherrypick supports modular testing with controlled memory use.
## Summary
- **get_it** demonstrates impressive speed and low overhead across all scenarios and loads, but lacks diagnostics, advanced scopes, and cycle detection.
- **cherrypick** is ideal for complex, multi-layered, production or testable architectures where scope, overrides, and diagnostics are critical. Predictably slower on deep/wide graphs, but scales well and provides extra safety.
**Recommendation:**
- Use cherrypick for enterprise, multi-feature/testable DI needs.
- Use get_it for fast games, scripts, tiny Apps, and hot demos.
_Last updated: August 8, 2025._

View File

@@ -1,79 +1,51 @@
# Результаты бенчмарка DI: cherrypick vs get_it
# Сравнительный отчет DI-бенчмарка: cherrypick vs get_it vs riverpod
## Параметры запуска бенчмарков
## Описание сценариев
| Параметр | Значение |
|------------------|-------------------------|
| --benchmark | all |
| --chainCount (-c)| 10, 100 |
| --nestingDepth (-d)| 10, 100 |
| --repeat (-r) | 2 |
| --warmup (-w) | 1 (по умолчанию) |
| --format (-f) | markdown |
| --di | cherrypick, get_it |
1. **RegisterSingleton** — регистрация и получение объекта-синглтона (базовая скорость DI).
2. **ChainSingleton** — цепочка зависимостей A → B → ... → N (singleton). Глубокий singleton-резолвинг.
3. **ChainFactory** — все элементы цепочки — фабрики. Stateless построение графа.
4. **AsyncChain** — асинхронная цепочка (async factory). Тестирует async/await граф.
5. **Named** — регистрация двух биндингов с именами, разрешение по имени.
6. **Override** — регистрация биндинга/цепочки в дочернем scope. Проверка override/scoping.
---
## Описание бенчмарков
## Сводная таблица: chainCount=10, nestingDepth=10 (Mean, PeakRSS)
**(1) RegisterSingleton**
Регистрируется и дважды резолвится singleton. Базовый тест скорости DI.
| Сценарий | cherrypick Mean (мкс) | cherrypick PeakRSS | get_it Mean (мкс) | get_it PeakRSS | riverpod Mean (мкс) | riverpod PeakRSS |
|--------------------|----------------------:|-------------------:|------------------:|---------------:|--------------------:|-----------------:|
| RegisterSingleton | 13.00 | 273104 | 8.40 | 261872 | 9.80 | 268512 |
| ChainSingleton | 13.80 | 271072 | 2.00 | 262000 | 33.60 | 268784 |
| ChainFactory | 5.00 | 299216 | 4.00 | 297136 | 22.80 | 271296 |
| AsyncChain | 28.60 | 290640 | 24.60 | 342976 | 78.20 | 285920 |
| Named | 2.20 | 297008 | 0.20 | 449824 | 6.20 | 281136 |
| Override | 7.00 | 297024 | 0.00 | 449824 | 30.20 | 281152 |
**(2) ChainSingleton**
Цепочка зависимостей A → B → ... → N (singleton). Тестирует скорость заполнения и разрешения глубоких singleton-цепочек по имени.
## Максимальная нагрузка: chainCount=100, nestingDepth=100 (Mean, PeakRSS)
**(3) ChainFactory**
Аналогично ChainSingleton, но каждое звено цепи — factory (новый объект при каждом resolve).
**(4) AsyncChain**
Асинхронная цепочка (async factory). Важно для сценариев с async DI.
**(5) Named**
Регистрируются две реализации по имени ('impl1', 'impl2'), разрешается named. Проверка lookup по имени.
**(6) Override**
Регистрируется цепочка/alias в дочернем scope, резолвится UniversalService без имени там же. Симуляция override и изолированной/тестовой архитектуры.
| Сценарий | cherrypick Mean (мкс) | cherrypick PeakRSS | get_it Mean (мкс) | get_it PeakRSS | riverpod Mean (мкс) | riverpod PeakRSS |
|--------------------|----------------------:|-------------------:|------------------:|---------------:|--------------------:|-----------------:|
| RegisterSingleton | 4.00 | 271072 | 1.00 | 262000 | 2.00 | 268688 |
| ChainSingleton | 76.60 | 303312 | 2.00 | 297136 | 221.80 | 270784 |
| ChainFactory | 80.00 | 293952 | 39.20 | 342720 | 195.80 | 308640 |
| AsyncChain | 251.40 | 297008 | 18.20 | 450640 | 748.80 | 285968 |
| Named | 2.20 | 297008 | 0.00 | 449824 | 1.00 | 281136 |
| Override | 104.80 | 301632 | 2.20 | 477344 | 120.80 | 294752 |
---
## Сравнительная таблица (Mean (us), ΔRSS(KB)), chainCount=10, nestingDepth=10
## Краткий анализ и рекомендации
| Сценарий | cherrypick Mean (мкс) | cherrypick ΔRSS | get_it Mean (мкс) | get_it ΔRSS |
|-------------------|---------------------:|----------------:|-----------------:|------------:|
| RegisterSingleton | 21.0 | 320 | 24.5 | 80 |
| ChainSingleton | 112.5 | -3008 | 2.0 | 304 |
| ChainFactory | 8.0 | 0 | 4.0 | 0 |
| AsyncChain | 36.5 | 0 | 13.5 | 0 |
| Named | 1.5 | 0 | 0.5 | 0 |
| Override | 27.5 | 0 | 0.0 | 0 |
- **get_it** всегда лидер, особенно на глубине/асинхронных графах.
- **cherrypick** заметно быстрее riverpod на сложных сценариях, опережая его в разы.
- **riverpod** подходит только для простых/небольших графов — при росте глубины или async/override резко проигрывает по скорости.
## Максимальная нагрузка: chainCount=100, nestingDepth=100
| Сценарий | cherrypick Mean (мкс) | cherrypick ΔRSS | get_it Mean (мкс) | get_it ΔRSS |
|-------------------|---------------------:|----------------:|-----------------:|------------:|
| RegisterSingleton | 1.0 | 32 | 1.0 | 0 |
| ChainSingleton | 3884.0 | 0 | 1.5 | 34848 |
| ChainFactory | 4088.0 | 0 | 50.0 | 12528 |
| AsyncChain | 4287.0 | 0 | 17.0 | 63120 |
| Named | 1.0 | 0 | 0.0 | 0 |
| Override | 4767.5 | 0 | 1.5 | 14976 |
### Рекомендации
- Используйте **get_it** для критичных к скорости приложений/сложных графов зависимостей.
- Выбирайте **cherrypick** для масштабируемых, тестируемых архитектур, если микросекундная разница не критична.
- **riverpod** уместен только для реактивного UI или простых графов DI.
---
## Пояснения по сценариям
- **RegisterSingleton** — базовый тест DI (регистрация и резолвинг singleton). Практически мгновенно у обоих DI.
- **ChainSingleton** — глубокая singleton-цепочка. get_it вне конкуренции по скорости, cherrypick медленнее из-за более сложной логики поиска именованных зависимостей, но предсказуем.
- **ChainFactory** — цепочка Factory-объектов. cherrypick заметно медленнее на длинных цепях, get_it почти не увеличивает время.
- **AsyncChain** — асинхронная цепочка сервисов. get_it существенно быстрее, cherrypick страдает на глубине/ширине.
- **Named** — разрешение зависимостей по имени. Оба DI почти мгновенны.
- **Override** — переопределение alias без имени в дочернем scope. get_it (со стековыми scope) почти не теряет времени; cherrypick предсказуемо замедляется на глубине/ширине.
## Итог
- **get_it** выдаёт отличную производительность по всем сценариям, особенно на больших графах; но не поддерживает продвинутую диагностику, проверки циклов, расширенные scope.
- **cherrypick** — незаменим для работы с корпоративными/тестируемыми архитектурами и наследованием, устойчиво ведёт себя на тысячи зависимостей, но требует учёта роста времени при экстремальных нагрузках.
**Рекомендация:**
- cherrypick — выбор для серьёзных production-систем и тестирования;
- get_it — лидер для MVP, быстрых демо, прототипов, CLI, games.
_Обновлено: 8 августа 2025_

View File

@@ -9,7 +9,6 @@ class RiverpodAdapter extends DIAdapter<Map<String, rp.ProviderBase<Object?>>> {
rp.ProviderContainer? _container;
final Map<String, rp.ProviderBase<Object?>> _namedProviders;
final rp.ProviderContainer? _parent;
final bool _isSubScope;
RiverpodAdapter({
rp.ProviderContainer? container,
@@ -18,8 +17,7 @@ class RiverpodAdapter extends DIAdapter<Map<String, rp.ProviderBase<Object?>>> {
bool isSubScope = false,
}) : _container = container,
_namedProviders = providers ?? <String, rp.ProviderBase<Object?>>{},
_parent = parent,
_isSubScope = isSubScope;
_parent = parent;
@override
void setupDependencies(void Function(Map<String, rp.ProviderBase<Object?>> container) registration) {

View File

@@ -47,7 +47,7 @@ packages:
path: "../cherrypick"
relative: true
source: path
version: "3.0.0-dev.2"
version: "3.0.0-dev.5"
collection:
dependency: transitive
description:

View File

@@ -1,3 +1,28 @@
## 3.0.0-dev.7
> Note: This release has breaking changes.
- **FIX**(comment): fix warnings.
- **FIX**(license): correct urls.
- **FEAT**: add Disposable interface source and usage example.
- **DOCS**(readme): add comprehensive section on annotations and DI code generation.
- **DOCS**(readme): add detailed section and examples for automatic Disposable resource cleanup\n\n- Added a dedicated section with English description and code samples on using Disposable for automatic resource management.\n- Updated Features to include automatic resource cleanup for Disposable dependencies.\n\nHelps developers understand and implement robust DI resource management practices.
- **DOCS**(faq): add best practice FAQ about using await with scope disposal.
- **DOCS**(faq): add best practice FAQ about using await with scope disposal.
- **BREAKING** **REFACTOR**(core): make closeRootScope async and await dispose.
- **BREAKING** **DOCS**(disposable): add detailed English documentation and usage examples for Disposable interface; chore: update binding_resolver and add explanatory comment in scope_test for deprecated usage.\n\n- Expanded Disposable interface docs, added sync & async example classes, and CherryPick integration sample.\n- Clarified how to implement and use Disposable in DI context.\n- Updated binding_resolver for internal improvements.\n- Added ignore for deprecated member use in scope_test for clarity and future upgrades.\n\nBREAKING CHANGE: Documentation style enhancement and clearer API usage for Disposable implementations.
## 3.0.0-dev.6
> Note: This release has breaking changes.
- **FIX**: improve global cycle detector logic.
- **DOCS**(readme): add comprehensive DI state and action logging to features.
- **DOCS**(helper): add complete DartDoc with real usage examples for CherryPick class.
- **DOCS**(log_format): add detailed English documentation for formatLogMessage function.
- **BREAKING** **FEAT**(core): refactor root scope API, improve logger injection, helpers, and tests.
- **BREAKING** **FEAT**(logger): add extensible logging API, usage examples, and bilingual documentation.
## 3.0.0-dev.5
- **REFACTOR**(scope): simplify _findBindingResolver<T> with one-liner and optional chaining.

View File

@@ -192,7 +192,7 @@
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,

View File

@@ -1,8 +1,92 @@
# CherryPick
`cherrypick` is a flexible and lightweight dependency injection library for Dart and Flutter. It provides an easy-to-use system for registering, scoping, and resolving dependencies using modular bindings and hierarchical scopes. The design enables cleaner architecture, testability, and modular code in your applications.
`cherrypick` is a flexible and lightweight dependency injection library for Dart and Flutter.
It provides an easy-to-use system for registering, scoping, and resolving dependencies using modular bindings and hierarchical scopes. The design enables cleaner architecture, testability, and modular code in your applications.
## Key Concepts
---
## Table of Contents
- [Key Features](#key-features)
- [Installation](#installation)
- [Getting Started](#getting-started)
- [Core Concepts](#core-concepts)
- [Binding](#binding)
- [Module](#module)
- [Scope](#scope)
- [Automatic Resource Cleanup with Disposable](#automatic-resource-cleanup-with-disposable)
- [Dependency Resolution API](#dependency-resolution-api)
- [Using Annotations & Code Generation](#using-annotations--code-generation)
- [Advanced Features](#advanced-features)
- [Hierarchical Subscopes](#hierarchical-subscopes)
- [Logging](#logging)
- [Circular Dependency Detection](#circular-dependency-detection)
- [Performance Improvements](#performance-improvements)
- [Example Application](#example-application)
- [FAQ](#faq)
- [Documentation Links](#documentation-links)
- [Contributing](#contributing)
- [License](#license)
---
## Key Features
- Main Scope and Named Subscopes
- Named Instance Binding and Resolution
- Asynchronous and Synchronous Providers
- Providers Supporting Runtime Parameters
- Singleton Lifecycle Management
- Modular and Hierarchical Composition
- Null-safe Resolution (tryResolve/tryResolveAsync)
- Circular Dependency Detection (Local and Global)
- Comprehensive logging of dependency injection state and actions
- Automatic resource cleanup for all registered Disposable dependencies
---
## Installation
Add to your `pubspec.yaml`:
```yaml
dependencies:
cherrypick: ^<latest_version>
```
Then run:
```shell
dart pub get
```
---
## Getting Started
Here is a minimal example that registers and resolves a dependency:
```dart
import 'package:cherrypick/cherrypick.dart';
class AppModule extends Module {
@override
void builder(Scope currentScope) {
bind<ApiClient>().toInstance(ApiClientMock());
bind<String>().toProvide(() => "Hello, CherryPick!");
}
}
final rootScope = CherryPick.openRootScope();
rootScope.installModules([AppModule()]);
final greeting = rootScope.resolve<String>();
print(greeting); // prints: Hello, CherryPick!
await CherryPick.closeRootScope();
```
---
## Core Concepts
### Binding
@@ -79,8 +163,108 @@ final str = rootScope.resolve<String>();
// Resolve a dependency asynchronously
final result = await rootScope.resolveAsync<String>();
// Close the root scope once done
CherryPick.closeRootScope();
// Recommended: Close the root scope and release all resources
await CherryPick.closeRootScope();
// Alternatively, you may manually call dispose on any scope you manage individually
// await rootScope.dispose();
```
---
### Automatic Resource Cleanup with Disposable
CherryPick can automatically clean up any dependency that implements the `Disposable` interface. This makes resource management (for controllers, streams, sockets, files, etc.) easy and reliable—especially when scopes or the app are shut down.
If you bind an object implementing `Disposable` as a singleton or provide it via the DI container, CherryPick will call its `dispose()` method when the scope is closed or cleaned up.
#### Key Points
- Supports both synchronous and asynchronous cleanup (dispose may return `void` or `Future`).
- All `Disposable` instances from the current scope and subscopes will be disposed in the correct order.
- Prevents resource leaks and enforces robust cleanup.
- No manual wiring needed once your class implements `Disposable`.
#### Minimal Sync Example
```dart
class CacheManager implements Disposable {
void dispose() {
cache.clear();
print('CacheManager disposed!');
}
}
final scope = CherryPick.openRootScope();
scope.installModules([
Module((bind) => bind<CacheManager>().toProvide(() => CacheManager()).singleton()),
]);
// ...later
await CherryPick.closeRootScope(); // prints: CacheManager disposed!
```
#### Async Example
```dart
class MyServiceWithSocket implements Disposable {
@override
Future<void> dispose() async {
await socket.close();
print('Socket closed!');
}
}
scope.installModules([
Module((bind) => bind<MyServiceWithSocket>().toProvide(() => MyServiceWithSocket()).singleton()),
]);
await CherryPick.closeRootScope(); // awaits async disposal
```
**Tip:** Always call `await CherryPick.closeRootScope()` or `await scope.closeSubScope(key)` in your shutdown/teardown logic to ensure all resources are released automatically.
---
### Automatic resource management (`Disposable`, `dispose`)
CherryPick automatically manages the lifecycle of any object registered via DI that implements the `Disposable` interface.
**Best practice:**
Always finish your work with `await CherryPick.closeRootScope()` (for the root scope) or `await scope.closeSubScope('key')` (for subscopes).
These methods will automatically await `dispose()` on all resolved objects (e.g., singletons) that implement `Disposable`, ensuring proper and complete resource cleanup—sync or async.
Manual `await scope.dispose()` may be useful if you manually manage custom scopes.
#### Example
```dart
class MyService implements Disposable {
@override
FutureOr<void> dispose() async {
// release resources, close streams, perform async shutdown, etc.
print('MyService disposed!');
}
}
final scope = openRootScope();
scope.installModules([
ModuleImpl(),
]);
final service = scope.resolve<MyService>();
// ... use service
// Recommended completion:
await CherryPick.closeRootScope(); // will print: MyService disposed!
// Or, to close and clean up a subscope and its resources:
await scope.closeSubScope('feature');
class ModuleImpl extends Module {
@override
void builder(Scope scope) {
bind<MyService>().toProvide(() => MyService()).singleton();
}
}
```
#### Working with Subscopes
@@ -101,6 +285,144 @@ final dataBloc = await subScope.resolveAsync<DataBloc>();
>
> This optimization is internal and does not change any library APIs or usage patterns, but it significantly improves resolution speed in larger applications.
---
## Using Annotations & Code Generation
CherryPick provides best-in-class developer ergonomics and type safety through **Dart annotations** and code generation. This lets you dramatically reduce boilerplate: simply annotate your classes, fields, and modules, run the code generator, and enjoy auto-wired dependency injection!
### How It Works
1. **Annotate** your services, providers, and fields using `cherrypick_annotations`.
2. **Generate** code using `cherrypick_generator` with `build_runner`.
3. **Use** generated modules and mixins for fully automated DI (dependency injection).
---
### Supported Annotations
| Annotation | Target | Description |
|-------------------|---------------|--------------------------------------------------------------------------------|
| `@injectable()` | class | Enables automatic field injection for this class (mixin will be generated) |
| `@inject()` | field | Field will be injected using DI (works with @injectable classes) |
| `@module()` | class | Declares a DI module; its methods can provide services/providers |
| `@provide` | method | Registers as a DI provider method (may have dependencies as parameters) |
| `@instance` | method/class | Registers an instance (new object on each resolution, i.e. factory) |
| `@singleton` | method/class | Registers as a singleton (one instance per scope) |
| `@named` | field/param | Use named instance (bind/resolve by name or apply to field/param) |
| `@scope` | field/param | Inject or resolve from a specific named scope |
| `@params` | param | Marks method parameter as filled by user-supplied runtime params at resolution |
You can easily **combine** these annotations for advanced scenarios!
---
### Field Injection Example
```dart
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
@injectable()
class ProfilePage with _\$ProfilePage {
@inject()
late final AuthService auth;
@inject()
@scope('profile')
late final ProfileManager manager;
@inject()
@named('admin')
late final UserService adminUserService;
}
```
- After running build_runner, the mixin `_5ProfilePage` will be generated for field injection.
- Call `myProfilePage.injectFields();` or use the mixin's auto-inject feature, and all dependencies will be set up for you.
---
### Module and Provider Example
```dart
@module()
abstract class AppModule {
@singleton
AuthService provideAuth(Api api) => AuthService(api);
@named('logging')
@provide
Future<Logger> provideLogger(@params Map<String, dynamic> args) async => ...;
}
```
- Mark class as `@module`, write provider methods.
- Use `@singleton`, `@named`, `@provide`, `@params` to control lifecycle, key names, and parameters.
- The generator will produce a class like `$AppModule` with the proper DI bindings.
---
### Usage Steps
1. **Add to your pubspec.yaml**:
```yaml
dependencies:
cherrypick: any
cherrypick_annotations: any
dev_dependencies:
cherrypick_generator: any
build_runner: any
```
2. **Annotate** your classes and modules as above.
3. **Run code generation:**
```shell
dart run build_runner build --delete-conflicting-outputs
# or in Flutter:
flutter pub run build_runner build --delete-conflicting-outputs
```
4. **Register modules and use auto-injection:**
```dart
final scope = CherryPick.openRootScope()
..installModules([$AppModule()]);
final profile = ProfilePage();
profile.injectFields(); // injects all @inject fields
```
---
### Advanced: Parameters, Named Instances, and Scopes
- Use `@named` for key-based multi-implementation injection.
- Use `@scope` when dependencies live in a non-root scope.
- Use `@params` for runtime arguments passed during resolution.
---
### Troubleshooting & Tips
- After modifying DI-related code, always re-run `build_runner`.
- Do not manually edit `.g.dart` files—let the generator manage them.
- Errors in annotation usage (e.g., using `@singleton` on wrong target) are shown at build time.
---
### References
- [Full annotation reference (en)](doc/annotations_en.md)
- [cherrypick_annotations/README.md](../cherrypick_annotations/README.md)
- [cherrypick_generator/README.md](../cherrypick_generator/README.md)
- See the [`examples/postly`](../examples/postly) for a full working DI+annotations app.
---
### Dependency Lookup API
- `resolve<T>()` — Locates a dependency instance or throws if missing.
@@ -234,6 +556,32 @@ class ApiClientImpl implements ApiClient {
}
```
## Logging
CherryPick supports centralized logging of all dependency injection (DI) events and errors. You can globally enable logs for your application or test environment with:
```dart
import 'package:cherrypick/cherrypick.dart';
void main() {
// Set a global logger before any scopes are created
CherryPick.setGlobalLogger(PrintLogger()); // or your custom logger
final scope = CherryPick.openRootScope();
// All DI actions and errors will now be logged!
}
```
- All dependency resolution, scope creation, module installation, and circular dependency errors will be sent to your logger (via info/error method).
- By default, logs are off (SilentLogger is used in production).
If you want fine-grained, test-local, or isolated logging, you can provide a logger directly to each scope:
```dart
final logger = MockLogger();
final scope = Scope(null, logger: logger); // works in tests for isolation
scope.installModules([...]);
```
## Features
- [x] Main Scope and Named Subscopes
@@ -244,6 +592,8 @@ class ApiClientImpl implements ApiClient {
- [x] Modular and Hierarchical Composition
- [x] Null-safe Resolution (tryResolve/tryResolveAsync)
- [x] Circular Dependency Detection (Local and Global)
- [x] Comprehensive logging of dependency injection state and actions
- [x] Automatic resource cleanup for all registered Disposable dependencies
## Quick Guide: Circular Dependency Detection
@@ -313,6 +663,14 @@ try {
**More details:** See [cycle_detection.en.md](doc/cycle_detection.en.md)
## FAQ
### Q: Do I need to use `await` with CherryPick.closeRootScope(), CherryPick.closeScope(), or scope.dispose() if I have no Disposable services?
**A:**
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.
## Documentation
- [Circular Dependency Detection (English)](doc/cycle_detection.en.md)
@@ -324,7 +682,7 @@ Contributions are welcome! Please open issues or submit pull requests on [GitHub
## License
Licensed under the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).
Licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0).
---

View File

@@ -47,7 +47,7 @@ class FeatureModule extends Module {
Future<void> main() async {
try {
final scope = openRootScope().installModules([AppModule()]);
final scope = CherryPick.openRootScope().installModules([AppModule()]);
final subScope = scope
.openSubScope("featureScope")

View File

@@ -0,0 +1,37 @@
import 'package:cherrypick/cherrypick.dart';
/// Example of a simple service class.
class UserRepository {
String getUserName() => 'Sergey DI';
}
/// DI module for registering dependencies.
class AppModule extends Module {
@override
void builder(Scope currentScope) {
bind<UserRepository>().toInstance(UserRepository());
}
}
void main() {
// Set a global logger for the DI system
CherryPick.setGlobalLogger(PrintLogger());
// Open the root scope
final rootScope = CherryPick.openRootScope();
// Register the DI module
rootScope.installModules([AppModule()]);
// Resolve a dependency (service)
final repo = rootScope.resolve<UserRepository>();
print('User: ${repo.getUserName()}');
// Work with a sub-scope (create/close)
final subScope = rootScope.openSubScope('feature.profile');
subScope.closeSubScope('feature.profile');
// Demonstrate disabling and re-enabling logging
CherryPick.setGlobalLogger(const SilentLogger());
rootScope.resolve<UserRepository>(); // now without logs
}

View File

@@ -126,7 +126,7 @@ void main() {
// Example 1: Demonstrate circular dependency
print('1. Attempt to create a scope with circular dependencies:');
try {
final scope = Scope(null);
final scope = CherryPick.openRootScope();
scope.enableCycleDetection(); // Включаем обнаружение циклических зависимостей
scope.installModules([
@@ -144,7 +144,7 @@ void main() {
// Example 2: Without circular dependency detection (dangerous!)
print('2. Same code without circular dependency detection:');
try {
final scope = Scope(null);
final scope = CherryPick.openRootScope();
// НЕ включаем обнаружение циклических зависимостей
scope.installModules([
@@ -166,7 +166,7 @@ void main() {
// Example 3: Correct architecture without circular dependencies
print('3. Correct architecture without circular dependencies:');
try {
final scope = Scope(null);
final scope = CherryPick.openRootScope();
scope.enableCycleDetection(); // Включаем для безопасности
scope.installModules([

View File

@@ -0,0 +1,40 @@
import 'package:cherrypick/cherrypick.dart';
/// Ваш сервис с освобождением ресурсов
class MyService implements Disposable {
bool wasDisposed = false;
@override
void dispose() {
// Например: закрыть соединение, остановить таймер, освободить память
wasDisposed = true;
print('MyService disposed!');
}
void doSomething() => print('Doing something...');
}
void main() {
final scope = CherryPick.openRootScope();
// Регистрируем биндинг (singleton для примера)
scope.installModules([
ModuleImpl(),
]);
// Получаем зависимость
final service = scope.resolve<MyService>();
service.doSomething(); // «Doing something...»
// Освобождаем все ресурсы
scope.dispose();
print('Service wasDisposed = ${service.wasDisposed}'); // true
}
/// Пример модуля CherryPick
class ModuleImpl extends Module {
@override
void builder(Scope scope) {
bind<MyService>().toProvide(() => MyService()).singleton();
}
}

View File

@@ -5,7 +5,7 @@ library;
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,3 +20,5 @@ export 'package:cherrypick/src/global_cycle_detector.dart';
export 'package:cherrypick/src/helper.dart';
export 'package:cherrypick/src/module.dart';
export 'package:cherrypick/src/scope.dart';
export 'package:cherrypick/src/logger.dart';
export 'package:cherrypick/src/disposable.dart';

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -13,17 +13,70 @@
import 'package:cherrypick/src/binding_resolver.dart';
/// RU: Класс Binding<T> настраивает параметры экземпляра.
/// ENG: The Binding<T> class configures the settings for the instance.
/// RU: Класс Binding&lt;T&gt; настраивает параметры экземпляра.
/// ENG: The Binding&lt;T&gt; class configures the settings for the instance.
///
import 'package:cherrypick/src/logger.dart';
import 'package:cherrypick/src/log_format.dart';
class Binding<T> {
late Type _key;
String? _name;
BindingResolver<T>? _resolver;
Binding() {
CherryPickLogger? logger;
// Deferred logging flags
bool _createdLogged = false;
bool _namedLogged = false;
bool _singletonLogged = false;
Binding({this.logger}) {
_key = T;
// Не логируем здесь! Делаем deferred лог после назначения logger
}
void markCreated() {
if (!_createdLogged) {
logger?.info(formatLogMessage(
type: 'Binding',
name: T.toString(),
params: _name != null ? {'name': _name} : null,
description: 'created',
));
_createdLogged = true;
}
}
void markNamed() {
if (isNamed && !_namedLogged) {
logger?.info(formatLogMessage(
type: 'Binding',
name: T.toString(),
params: {'name': _name},
description: 'named',
));
_namedLogged = true;
}
}
void markSingleton() {
if (isSingleton && !_singletonLogged) {
logger?.info(formatLogMessage(
type: 'Binding',
name: T.toString(),
params: _name != null ? {'name': _name} : null,
description: 'singleton mode enabled',
));
_singletonLogged = true;
}
}
void logAllDeferred() {
markCreated();
markNamed();
markSingleton();
}
/// RU: Метод возвращает тип экземпляра.
@@ -58,6 +111,7 @@ class Binding<T> {
/// return [Binding]
Binding<T> withName(String name) {
_name = name;
// Не логируем здесь, deferred log via markNamed()
return this;
}
@@ -67,7 +121,6 @@ class Binding<T> {
/// return [Binding]
Binding<T> toInstance(Instance<T> value) {
_resolver = InstanceResolver<T>(value);
return this;
}
@@ -77,7 +130,6 @@ class Binding<T> {
/// return [Binding]
Binding<T> toProvide(Provider<T> value) {
_resolver = ProviderResolver<T>((_) => value.call(), withParams: false);
return this;
}
@@ -87,7 +139,6 @@ class Binding<T> {
/// return [Binding]
Binding<T> toProvideWithParams(ProviderWithParams<T> value) {
_resolver = ProviderResolver<T>(value, withParams: true);
return this;
}
@@ -112,15 +163,73 @@ class Binding<T> {
/// return [Binding]
Binding<T> singleton() {
_resolver?.toSingleton();
// Не логируем здесь, deferred log via markSingleton()
return this;
}
T? resolveSync([dynamic params]) {
return resolver?.resolveSync(params);
final res = resolver?.resolveSync(params);
if (res != null) {
logger?.info(formatLogMessage(
type: 'Binding',
name: T.toString(),
params: {
if (_name != null) 'name': _name,
'method': 'resolveSync',
},
description: 'object created/resolved',
));
} else {
logger?.warn(formatLogMessage(
type: 'Binding',
name: T.toString(),
params: {
if (_name != null) 'name': _name,
'method': 'resolveSync',
},
description: 'resolveSync returned null',
));
}
return res;
}
Future<T>? resolveAsync([dynamic params]) {
return resolver?.resolveAsync(params);
final future = resolver?.resolveAsync(params);
if (future != null) {
future
.then((res) => logger?.info(formatLogMessage(
type: 'Binding',
name: T.toString(),
params: {
if (_name != null) 'name': _name,
'method': 'resolveAsync',
},
description: 'Future resolved',
)))
.catchError((e, s) => logger?.error(
formatLogMessage(
type: 'Binding',
name: T.toString(),
params: {
if (_name != null) 'name': _name,
'method': 'resolveAsync',
},
description: 'resolveAsync error',
),
e,
s,
));
} else {
logger?.warn(formatLogMessage(
type: 'Binding',
name: T.toString(),
params: {
if (_name != null) 'name': _name,
'method': 'resolveAsync',
},
description: 'resolveAsync returned null',
));
}
return future;
}
}

View File

@@ -1,3 +1,16 @@
//
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import 'dart:async';
typedef Instance<T> = FutureOr<T>;

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -12,6 +12,8 @@
//
import 'dart:collection';
import 'package:cherrypick/src/logger.dart';
import 'package:cherrypick/src/log_format.dart';
/// RU: Исключение, выбрасываемое при обнаружении циклической зависимости.
/// ENG: Exception thrown when a circular dependency is detected.
@@ -19,7 +21,10 @@ class CircularDependencyException implements Exception {
final String message;
final List<String> dependencyChain;
const CircularDependencyException(this.message, this.dependencyChain);
CircularDependencyException(this.message, this.dependencyChain) {
// DEBUG
}
@override
String toString() {
@@ -31,24 +36,37 @@ class CircularDependencyException implements Exception {
/// RU: Детектор циклических зависимостей для CherryPick DI контейнера.
/// ENG: Circular dependency detector for CherryPick DI container.
class CycleDetector {
// Стек текущих разрешаемых зависимостей
final CherryPickLogger _logger;
final Set<String> _resolutionStack = HashSet<String>();
// История разрешения для построения цепочки зависимостей
final List<String> _resolutionHistory = [];
CycleDetector({required CherryPickLogger logger}): _logger = logger;
/// RU: Начинает отслеживание разрешения зависимости.
/// ENG: Starts tracking dependency resolution.
///
/// Throws [CircularDependencyException] if circular dependency is detected.
void startResolving<T>({String? named}) {
final dependencyKey = _createDependencyKey<T>(named);
print('[DEBUG] CycleDetector logger type=${_logger.runtimeType} hash=${_logger.hashCode}');
_logger.info(formatLogMessage(
type: 'CycleDetector',
name: dependencyKey.toString(),
params: {'event': 'startResolving', 'stackSize': _resolutionStack.length},
description: 'start resolving',
));
if (_resolutionStack.contains(dependencyKey)) {
// Найдена циклическая зависимость
final cycleStartIndex = _resolutionHistory.indexOf(dependencyKey);
final cycle = _resolutionHistory.sublist(cycleStartIndex)..add(dependencyKey);
// print removed (trace)
final msg = formatLogMessage(
type: 'CycleDetector',
name: dependencyKey.toString(),
params: {'chain': cycle.join('->')},
description: 'cycle detected',
);
_logger.error(msg);
throw CircularDependencyException(
'Circular dependency detected for $dependencyKey',
cycle,
@@ -63,8 +81,13 @@ class CycleDetector {
/// ENG: Finishes tracking dependency resolution.
void finishResolving<T>({String? named}) {
final dependencyKey = _createDependencyKey<T>(named);
_logger.info(formatLogMessage(
type: 'CycleDetector',
name: dependencyKey.toString(),
params: {'event': 'finishResolving'},
description: 'finish resolving',
));
_resolutionStack.remove(dependencyKey);
// Удаляем из истории только если это последний элемент
if (_resolutionHistory.isNotEmpty &&
_resolutionHistory.last == dependencyKey) {
@@ -75,6 +98,11 @@ class CycleDetector {
/// RU: Очищает все состояние детектора.
/// ENG: Clears all detector state.
void clear() {
_logger.info(formatLogMessage(
type: 'CycleDetector',
params: {'event': 'clear'},
description: 'resolution stack cleared',
));
_resolutionStack.clear();
_resolutionHistory.clear();
}
@@ -102,17 +130,28 @@ class CycleDetector {
/// ENG: Mixin for adding circular dependency detection support.
mixin CycleDetectionMixin {
CycleDetector? _cycleDetector;
CherryPickLogger get logger;
/// RU: Включает обнаружение циклических зависимостей.
/// ENG: Enables circular dependency detection.
void enableCycleDetection() {
_cycleDetector = CycleDetector();
_cycleDetector = CycleDetector(logger: logger);
logger.info(formatLogMessage(
type: 'CycleDetection',
params: {'event': 'enable'},
description: 'cycle detection enabled',
));
}
/// RU: Отключает обнаружение циклических зависимостей.
/// ENG: Disables circular dependency detection.
void disableCycleDetection() {
_cycleDetector?.clear();
logger.info(formatLogMessage(
type: 'CycleDetection',
params: {'event': 'disable'},
description: 'cycle detection disabled',
));
_cycleDetector = null;
}
@@ -139,7 +178,12 @@ mixin CycleDetectionMixin {
final cycleStartIndex = _cycleDetector!._resolutionHistory.indexOf(dependencyKey);
final cycle = _cycleDetector!._resolutionHistory.sublist(cycleStartIndex)
..add(dependencyKey);
logger.error(formatLogMessage(
type: 'CycleDetector',
name: dependencyKey.toString(),
params: {'chain': cycle.join('->')},
description: 'cycle detected',
));
throw CircularDependencyException(
'Circular dependency detected for $dependencyKey',
cycle,

View File

@@ -0,0 +1,63 @@
//
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import 'dart:async';
/// An interface for resources that require explicit cleanup, used by the CherryPick dependency injection container.
///
/// If an object implements [Disposable], the CherryPick DI container will automatically call [dispose]
/// when the corresponding scope is cleaned up. Use [Disposable] for closing streams, files, controllers, services, etc.
/// Both synchronous and asynchronous cleanup is supported:
/// - For sync disposables, implement [dispose] as a `void` or simply return nothing.
/// - For async disposables, implement [dispose] returning a [Future].
///
/// Example: Synchronous Disposable
/// ```dart
/// class MyLogger implements Disposable {
/// void dispose() {
/// print('Logger closed!');
/// }
/// }
/// ```
///
/// Example: Asynchronous Disposable
/// ```dart
/// class MyConnection implements Disposable {
/// @override
/// Future<void> dispose() async {
/// await connection.close();
/// }
/// }
/// ```
///
/// Usage with CherryPick DI Module
/// ```dart
/// final scope = openRootScope();
/// scope.installModules([
/// Module((b) {
/// b.bind<MyLogger>((_) => MyLogger());
/// b.bindAsync<MyConnection>((_) async => MyConnection());
/// }),
/// ]);
/// // ...
/// await scope.close(); // will automatically call dispose on all Disposables
/// ```
///
/// This pattern ensures that all resources are released safely and automatically when the scope is destroyed.
abstract class Disposable {
/// Releases all resources held by this object.
///
/// Implement cleanup logic (closing streams, sockets, files, etc.) within this method.
/// Return a [Future] for async cleanup, or nothing (`void`) for synchronous cleanup.
FutureOr<void> dispose();
}

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -12,13 +12,17 @@
//
import 'dart:collection';
import 'package:cherrypick/src/cycle_detector.dart';
import 'package:cherrypick/cherrypick.dart';
import 'package:cherrypick/src/log_format.dart';
/// RU: Глобальный детектор циклических зависимостей для всей иерархии скоупов.
/// ENG: Global circular dependency detector for entire scope hierarchy.
class GlobalCycleDetector {
static GlobalCycleDetector? _instance;
final CherryPickLogger _logger;
// Глобальный стек разрешения зависимостей
final Set<String> _globalResolutionStack = HashSet<String>();
@@ -28,12 +32,12 @@ class GlobalCycleDetector {
// Карта активных детекторов по скоупам
final Map<String, CycleDetector> _scopeDetectors = HashMap<String, CycleDetector>();
GlobalCycleDetector._internal();
GlobalCycleDetector._internal({required CherryPickLogger logger}): _logger = logger;
/// RU: Получить единственный экземпляр глобального детектора.
/// ENG: Get singleton instance of global detector.
static GlobalCycleDetector get instance {
_instance ??= GlobalCycleDetector._internal();
_instance ??= GlobalCycleDetector._internal(logger: CherryPick.globalLogger);
return _instance!;
}
@@ -55,7 +59,12 @@ class GlobalCycleDetector {
// Найдена глобальная циклическая зависимость
final cycleStartIndex = _globalResolutionHistory.indexOf(dependencyKey);
final cycle = _globalResolutionHistory.sublist(cycleStartIndex)..add(dependencyKey);
_logger.error(formatLogMessage(
type: 'CycleDetector',
name: dependencyKey.toString(),
params: {'chain': cycle.join('->')},
description: 'cycle detected',
));
throw CircularDependencyException(
'Global circular dependency detected for $dependencyKey',
cycle,
@@ -93,7 +102,12 @@ class GlobalCycleDetector {
final cycleStartIndex = _globalResolutionHistory.indexOf(dependencyKey);
final cycle = _globalResolutionHistory.sublist(cycleStartIndex)
..add(dependencyKey);
_logger.error(formatLogMessage(
type: 'CycleDetector',
name: dependencyKey.toString(),
params: {'chain': cycle.join('->')},
description: 'cycle detected',
));
throw CircularDependencyException(
'Global circular dependency detected for $dependencyKey',
cycle,
@@ -117,7 +131,7 @@ class GlobalCycleDetector {
/// RU: Получить детектор для конкретного скоупа.
/// ENG: Get detector for specific scope.
CycleDetector getScopeDetector(String scopeId) {
return _scopeDetectors.putIfAbsent(scopeId, () => CycleDetector());
return _scopeDetectors.putIfAbsent(scopeId, () => CycleDetector(logger: CherryPick.globalLogger));
}
/// RU: Удалить детектор для скоупа.

View File

@@ -3,77 +3,120 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import 'package:cherrypick/src/scope.dart';
import 'package:cherrypick/src/global_cycle_detector.dart';
import 'package:cherrypick/src/logger.dart';
import 'package:meta/meta.dart';
Scope? _rootScope;
/// Global logger for all [Scope]s managed by [CherryPick].
///
/// Defaults to [SilentLogger] unless set via [setGlobalLogger].
CherryPickLogger _globalLogger = const SilentLogger();
/// Whether global local-cycle detection is enabled for all Scopes ([Scope.enableCycleDetection]).
bool _globalCycleDetectionEnabled = false;
/// Whether global cross-scope cycle detection is enabled ([Scope.enableGlobalCycleDetection]).
bool _globalCrossScopeCycleDetectionEnabled = false;
/// Static facade for managing dependency graph, root scope, subscopes, logger, and global settings in the CherryPick DI container.
///
/// - Provides a singleton root scope for simple integration.
/// - Supports hierarchical/named subscopes by string path.
/// - Manages global/protected logging and DI diagnostics.
/// - Suitable for most application & CLI scenarios. For test isolation, manually create [Scope]s instead.
///
/// ### Example: Opening a root scope and installing modules
/// ```dart
/// class AppModule extends Module {
/// @override
/// void builder(Scope scope) {
/// scope.bind<Service>().toProvide(() => ServiceImpl());
/// }
/// }
///
/// final root = CherryPick.openRootScope();
/// root.installModules([AppModule()]);
/// final service = root.resolve<Service>();
/// ```
class CherryPick {
/// RU: Метод открывает главный [Scope].
/// ENG: The method opens the main [Scope].
/// Sets the global logger for all [Scope]s created by CherryPick.
///
/// return
static Scope openRootScope() {
_rootScope ??= Scope(null);
/// Allows customizing log output and DI diagnostics globally.
///
/// Example:
/// ```dart
/// CherryPick.setGlobalLogger(DefaultLogger());
/// ```
static void setGlobalLogger(CherryPickLogger logger) {
_globalLogger = logger;
}
// Применяем глобальную настройку обнаружения циклических зависимостей
/// Returns the current global logger used by CherryPick.
static CherryPickLogger get globalLogger => _globalLogger;
/// Returns the singleton root [Scope], creating it if needed.
///
/// Applies configured [globalLogger] and cycle detection settings.
///
/// Example:
/// ```dart
/// final root = CherryPick.openRootScope();
/// ```
static Scope openRootScope() {
_rootScope ??= Scope(null, logger: _globalLogger);
// Apply cycle detection settings
if (_globalCycleDetectionEnabled && !_rootScope!.isCycleDetectionEnabled) {
_rootScope!.enableCycleDetection();
}
// Применяем глобальную настройку обнаружения между скоупами
if (_globalCrossScopeCycleDetectionEnabled && !_rootScope!.isGlobalCycleDetectionEnabled) {
_rootScope!.enableGlobalCycleDetection();
}
return _rootScope!;
}
/// RU: Метод закрывает главный [Scope].
/// ENG: The method close the main [Scope].
/// Disposes and resets the root [Scope] singleton.
///
/// Call before tests or when needing full re-initialization.
///
static void closeRootScope() {
/// Example:
/// ```dart
/// CherryPick.closeRootScope();
/// ```
static Future<void> closeRootScope() async {
if (_rootScope != null) {
await _rootScope!.dispose(); // Автоматический вызов dispose для rootScope!
_rootScope = null;
}
}
/// RU: Глобально включает обнаружение циклических зависимостей для всех новых скоупов.
/// ENG: Globally enables circular dependency detection for all new scopes.
/// Globally enables cycle detection for all new [Scope]s created by CherryPick.
///
/// Этот метод влияет на все скоупы, создаваемые через CherryPick.
/// This method affects all scopes created through CherryPick.
/// Strongly recommended for safety in all projects.
///
/// Example:
/// ```dart
/// CherryPick.enableGlobalCycleDetection();
/// final scope = CherryPick.openRootScope(); // Автоматически включено обнаружение
/// ```
static void enableGlobalCycleDetection() {
_globalCycleDetectionEnabled = true;
// Включаем для уже существующего root scope, если он есть
if (_rootScope != null) {
_rootScope!.enableCycleDetection();
}
}
/// RU: Глобально отключает обнаружение циклических зависимостей.
/// ENG: Globally disables circular dependency detection.
///
/// Рекомендуется использовать в production для максимальной производительности.
/// Recommended for production use for maximum performance.
/// Disables global local cycle detection. Existing and new scopes won't check for local cycles.
///
/// Example:
/// ```dart
@@ -81,85 +124,63 @@ class CherryPick {
/// ```
static void disableGlobalCycleDetection() {
_globalCycleDetectionEnabled = false;
// Отключаем для уже существующего root scope, если он есть
if (_rootScope != null) {
_rootScope!.disableCycleDetection();
}
}
/// RU: Проверяет, включено ли глобальное обнаружение циклических зависимостей.
/// ENG: Checks if global circular dependency detection is enabled.
///
/// return true если включено, false если отключено
/// return true if enabled, false if disabled
/// Returns `true` if global local cycle detection is enabled.
static bool get isGlobalCycleDetectionEnabled => _globalCycleDetectionEnabled;
/// RU: Включает обнаружение циклических зависимостей для конкретного скоупа.
/// ENG: Enables circular dependency detection for a specific scope.
/// Enables cycle detection for a particular scope tree.
///
/// [scopeName] - имя скоупа (пустая строка для root scope)
/// [scopeName] - scope name (empty string for root scope)
/// [scopeName] - hierarchical string path (e.g. 'feature.api'), or empty for root.
/// [separator] - path separator (default: '.'), e.g. '/' for "feature/api/module"
///
/// Example:
/// ```dart
/// CherryPick.enableCycleDetectionForScope(); // Для root scope
/// CherryPick.enableCycleDetectionForScope(scopeName: 'feature.auth'); // Для конкретного scope
/// CherryPick.enableCycleDetectionForScope(scopeName: 'api.feature');
/// ```
static void enableCycleDetectionForScope({String scopeName = '', String separator = '.'}) {
final scope = _getScope(scopeName, separator);
scope.enableCycleDetection();
}
/// RU: Отключает обнаружение циклических зависимостей для конкретного скоупа.
/// ENG: Disables circular dependency detection for a specific scope.
///
/// [scopeName] - имя скоупа (пустая строка для root scope)
/// [scopeName] - scope name (empty string for root scope)
/// Disables cycle detection for a given scope. See [enableCycleDetectionForScope].
static void disableCycleDetectionForScope({String scopeName = '', String separator = '.'}) {
final scope = _getScope(scopeName, separator);
scope.disableCycleDetection();
}
/// RU: Проверяет, включено ли обнаружение циклических зависимостей для конкретного скоупа.
/// ENG: Checks if circular dependency detection is enabled for a specific scope.
/// Returns `true` if cycle detection is enabled for the requested scope.
///
/// [scopeName] - имя скоупа (пустая строка для root scope)
/// [scopeName] - scope name (empty string for root scope)
///
/// return true если включено, false если отключено
/// return true if enabled, false if disabled
/// Example:
/// ```dart
/// CherryPick.isCycleDetectionEnabledForScope(scopeName: 'feature.api');
/// ```
static bool isCycleDetectionEnabledForScope({String scopeName = '', String separator = '.'}) {
final scope = _getScope(scopeName, separator);
return scope.isCycleDetectionEnabled;
}
/// RU: Возвращает текущую цепочку разрешения зависимостей для конкретного скоупа.
/// ENG: Returns current dependency resolution chain for a specific scope.
/// Returns the current dependency resolution chain inside the given scope.
///
/// Полезно для отладки и анализа зависимостей.
/// Useful for debugging and dependency analysis.
/// Useful for diagnostics (to print what types are currently resolving).
///
/// [scopeName] - имя скоупа (пустая строка для root scope)
/// [scopeName] - scope name (empty string for root scope)
///
/// return список имен зависимостей в текущей цепочке разрешения
/// return list of dependency names in current resolution chain
/// Example:
/// ```dart
/// print(CherryPick.getCurrentResolutionChain(scopeName: 'feature.api'));
/// ```
static List<String> getCurrentResolutionChain({String scopeName = '', String separator = '.'}) {
final scope = _getScope(scopeName, separator);
return scope.currentResolutionChain;
}
/// RU: Создает новый скоуп с автоматически включенным обнаружением циклических зависимостей.
/// ENG: Creates a new scope with automatically enabled circular dependency detection.
///
/// Удобный метод для создания безопасных скоупов в development режиме.
/// Convenient method for creating safe scopes in development mode.
/// Opens the root scope and enables local cycle detection.
///
/// Example:
/// ```dart
/// final scope = CherryPick.openSafeRootScope();
/// // Обнаружение циклических зависимостей автоматически включено
/// final safeRoot = CherryPick.openSafeRootScope();
/// ```
static Scope openSafeRootScope() {
final scope = openRootScope();
@@ -167,16 +188,11 @@ class CherryPick {
return scope;
}
/// RU: Создает новый дочерний скоуп с автоматически включенным обнаружением циклических зависимостей.
/// ENG: Creates a new child scope with automatically enabled circular dependency detection.
///
/// [scopeName] - имя скоупа
/// [scopeName] - scope name
/// Opens a named/nested scope and enables local cycle detection for it.
///
/// Example:
/// ```dart
/// final scope = CherryPick.openSafeScope(scopeName: 'feature.auth');
/// // Обнаружение циклических зависимостей автоматически включено
/// final api = CherryPick.openSafeScope(scopeName: 'feature.api');
/// ```
static Scope openSafeScope({String scopeName = '', String separator = '.'}) {
final scope = openScope(scopeName: scopeName, separator: separator);
@@ -184,8 +200,8 @@ class CherryPick {
return scope;
}
/// RU: Внутренний метод для получения скоупа по имени.
/// ENG: Internal method to get scope by name.
/// Returns a [Scope] by path (or the root if none specified).
/// Used for internal diagnostics & helpers.
static Scope _getScope(String scopeName, String separator) {
if (scopeName.isEmpty) {
return openRootScope();
@@ -193,91 +209,76 @@ class CherryPick {
return openScope(scopeName: scopeName, separator: separator);
}
/// RU: Метод открывает дочерний [Scope].
/// ENG: The method open the child [Scope].
/// Opens (and creates nested subscopes if needed) a scope by hierarchical path.
///
/// Дочерний [Scope] открывается с [scopeName]
/// Child [Scope] open with [scopeName]
/// [scopeName] - dot-separated path ("api.feature"). Empty = root.
/// [separator] - path delimiter (default: '.')
///
/// Applies global cycle detection settings to the returned scope.
///
/// Example:
/// ```dart
/// final apiScope = CherryPick.openScope(scopeName: 'network.super.api');
/// ```
/// final String scopeName = 'firstScope.secondScope';
/// final subScope = CherryPick.openScope(scopeName);
/// ```
///
///
@experimental
static Scope openScope({String scopeName = '', String separator = '.'}) {
if (scopeName.isEmpty) {
return openRootScope();
}
final nameParts = scopeName.split(separator);
if (nameParts.isEmpty) {
throw Exception('Can not open sub scope because scopeName can not split');
}
final scope = nameParts.fold(
openRootScope(),
(Scope previousValue, String element) =>
previousValue.openSubScope(element));
// Применяем глобальную настройку обнаружения циклических зависимостей
(Scope previous, String element) => previous.openSubScope(element)
);
if (_globalCycleDetectionEnabled && !scope.isCycleDetectionEnabled) {
scope.enableCycleDetection();
}
// Применяем глобальную настройку обнаружения между скоупами
if (_globalCrossScopeCycleDetectionEnabled && !scope.isGlobalCycleDetectionEnabled) {
scope.enableGlobalCycleDetection();
}
return scope;
}
/// RU: Метод открывает дочерний [Scope].
/// ENG: The method open the child [Scope].
/// Closes a named or root scope (if [scopeName] is omitted).
///
/// Дочерний [Scope] открывается с [scopeName]
/// Child [Scope] open with [scopeName]
/// [scopeName] - dot-separated hierarchical path (e.g. 'api.feature'). Empty = root.
/// [separator] - path delimiter.
///
/// Example:
/// ```dart
/// CherryPick.closeScope(scopeName: 'network.super.api');
/// ```
/// final String scopeName = 'firstScope.secondScope';
/// final subScope = CherryPick.closeScope(scopeName);
/// ```
///
///
@experimental
static void closeScope({String scopeName = '', String separator = '.'}) {
static Future<void> closeScope({String scopeName = '', String separator = '.'}) async {
if (scopeName.isEmpty) {
closeRootScope();
await closeRootScope();
return;
}
final nameParts = scopeName.split(separator);
if (nameParts.isEmpty) {
throw Exception(
'Can not close sub scope because scopeName can not split');
throw Exception('Can not close sub scope because scopeName can not split');
}
if (nameParts.length > 1) {
final lastPart = nameParts.removeLast();
final scope = nameParts.fold(
openRootScope(),
(Scope previousValue, String element) =>
previousValue.openSubScope(element));
scope.closeSubScope(lastPart);
(Scope previous, String element) => previous.openSubScope(element)
);
await scope.closeSubScope(lastPart);
} else {
openRootScope().closeSubScope(nameParts[0]);
await openRootScope().closeSubScope(nameParts.first);
}
}
/// RU: Глобально включает обнаружение циклических зависимостей между скоупами.
/// ENG: Globally enables cross-scope circular dependency detection.
/// Enables cross-scope cycle detection globally.
///
/// Этот режим обнаруживает циклические зависимости во всей иерархии скоупов.
/// This mode detects circular dependencies across the entire scope hierarchy.
/// This will activate detection of cycles that may span across multiple scopes
/// in the entire dependency graph. All new and existing [Scope]s will participate.
///
/// Strongly recommended for complex solutions with modular architecture.
///
/// Example:
/// ```dart
@@ -285,15 +286,15 @@ class CherryPick {
/// ```
static void enableGlobalCrossScopeCycleDetection() {
_globalCrossScopeCycleDetectionEnabled = true;
// Включаем для уже существующего root scope, если он есть
if (_rootScope != null) {
_rootScope!.enableGlobalCycleDetection();
}
}
/// RU: Глобально отключает обнаружение циклических зависимостей между скоупами.
/// ENG: Globally disables cross-scope circular dependency detection.
/// Disables global cross-scope cycle detection.
///
/// Existing and new scopes stop checking for global (cross-scope) cycles.
/// The internal global cycle detector will be cleared as well.
///
/// Example:
/// ```dart
@@ -301,54 +302,55 @@ class CherryPick {
/// ```
static void disableGlobalCrossScopeCycleDetection() {
_globalCrossScopeCycleDetectionEnabled = false;
// Отключаем для уже существующего root scope, если он есть
if (_rootScope != null) {
_rootScope!.disableGlobalCycleDetection();
}
// Очищаем глобальный детектор
GlobalCycleDetector.instance.clear();
}
/// RU: Проверяет, включено ли глобальное обнаружение циклических зависимостей между скоупами.
/// ENG: Checks if global cross-scope circular dependency detection is enabled.
/// Returns `true` if global cross-scope cycle detection is enabled.
///
/// return true если включено, false если отключено
/// return true if enabled, false if disabled
/// Example:
/// ```dart
/// if (CherryPick.isGlobalCrossScopeCycleDetectionEnabled) {
/// print('Global cross-scope detection is ON');
/// }
/// ```
static bool get isGlobalCrossScopeCycleDetectionEnabled => _globalCrossScopeCycleDetectionEnabled;
/// RU: Возвращает глобальную цепочку разрешения зависимостей.
/// ENG: Returns global dependency resolution chain.
/// Returns the current global dependency resolution chain (across all scopes).
///
/// Полезно для отладки циклических зависимостей между скоупами.
/// Useful for debugging circular dependencies across scopes.
/// Shows the cross-scope resolution stack, which is useful for advanced diagnostics
/// and debugging cycle issues that occur between scopes.
///
/// return список имен зависимостей в глобальной цепочке разрешения
/// return list of dependency names in global resolution chain
/// Example:
/// ```dart
/// print(CherryPick.getGlobalResolutionChain());
/// ```
static List<String> getGlobalResolutionChain() {
return GlobalCycleDetector.instance.globalResolutionChain;
}
/// RU: Очищает все состояние глобального детектора циклических зависимостей.
/// ENG: Clears all global circular dependency detector state.
/// Clears the global cross-scope cycle detector.
///
/// Полезно для тестов и сброса состояния.
/// Useful for tests and state reset.
/// Useful in tests or when resetting application state.
///
/// Example:
/// ```dart
/// CherryPick.clearGlobalCycleDetector();
/// ```
static void clearGlobalCycleDetector() {
GlobalCycleDetector.reset();
}
/// RU: Создает новый скоуп с автоматически включенным глобальным обнаружением циклических зависимостей.
/// ENG: Creates a new scope with automatically enabled global circular dependency detection.
/// Opens the root scope with both local and global cross-scope cycle detection enabled.
///
/// Этот скоуп будет отслеживать циклические зависимости во всей иерархии.
/// This scope will track circular dependencies across the entire hierarchy.
/// This is the safest way to start IoC for most apps — cycles will be detected
/// both inside a single scope and between scopes.
///
/// Example:
/// ```dart
/// final scope = CherryPick.openGlobalSafeRootScope();
/// // Глобальное обнаружение циклических зависимостей автоматически включено
/// final root = CherryPick.openGlobalSafeRootScope();
/// ```
static Scope openGlobalSafeRootScope() {
final scope = openRootScope();
@@ -357,16 +359,13 @@ class CherryPick {
return scope;
}
/// RU: Создает новый дочерний скоуп с автоматически включенным глобальным обнаружением циклических зависимостей.
/// ENG: Creates a new child scope with automatically enabled global circular dependency detection.
/// Opens the given named/nested scope and enables both local and cross-scope cycle detection on it.
///
/// [scopeName] - имя скоупа
/// [scopeName] - scope name
/// Recommended when creating feature/module scopes in large apps.
///
/// Example:
/// ```dart
/// final scope = CherryPick.openGlobalSafeScope(scopeName: 'feature.auth');
/// // Глобальное обнаружение циклических зависимостей автоматически включено
/// final featureScope = CherryPick.openGlobalSafeScope(scopeName: 'featureA.api');
/// ```
static Scope openGlobalSafeScope({String scopeName = '', String separator = '.'}) {
final scope = openScope(scopeName: scopeName, separator: separator);

View File

@@ -0,0 +1,55 @@
//
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/// Formats a log message string for CherryPick's logging system.
///
/// This function provides a unified structure for framework logs (info, warn, error, debug, etc.),
/// making it easier to parse and analyze events related to DI operations such as resolving bindings,
/// scope creation, module installation, etc.
///
/// All parameters except [name] and [params] are required.
///
/// Example:
/// ```dart
/// final msg = formatLogMessage(
/// type: 'Binding',
/// name: 'MyService',
/// params: {'parent': 'AppModule', 'lifecycle': 'singleton'},
/// description: 'created',
/// );
/// // Result: [Binding:MyService] parent=AppModule lifecycle=singleton created
/// ```
///
/// Parameters:
/// - [type]: The type of the log event subject (e.g., 'Binding', 'Scope', 'Module'). Required.
/// - [name]: Optional name of the subject (binding/scope/module) to disambiguate multiple instances/objects.
/// - [params]: Optional map for additional context (e.g., id, parent, lifecycle, named, etc.).
/// - [description]: Concise description of the event. Required.
///
/// Returns a structured string:
/// [type(:name)] param1=val1 param2=val2 ... description
String formatLogMessage({
required String type, // Binding, Scope, Module, ...
String? name, // Имя binding/scope/module
Map<String, Object?>? params, // Дополнительные параметры (id, parent, named и др.)
required String description, // Краткое описание события
}) {
final label = name != null ? '$type:$name' : type;
final paramsStr = (params != null && params.isNotEmpty)
? params.entries.map((e) => '${e.key}=${e.value}').join(' ')
: '';
return '[$label]'
'${paramsStr.isNotEmpty ? ' $paramsStr' : ''}'
' $description';
}

View File

@@ -0,0 +1,108 @@
//
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/// ----------------------------------------------------------------------------
/// CherryPickLogger — интерфейс для логирования событий DI в CherryPick.
///
/// ENGLISH:
/// Interface for dependency injection (DI) logger in CherryPick. Allows you to
/// receive information about the internal events and errors in the DI system.
/// Your implementation can use any logging framework or UI.
///
/// RUSSIAN:
/// Интерфейс логгера для DI-контейнера CherryPick. Позволяет получать
/// сообщения о работе DI-контейнера, его ошибках и событиях, и
/// интегрировать любые готовые решения для логирования/сбора ошибок.
/// ----------------------------------------------------------------------------
abstract class CherryPickLogger {
/// ----------------------------------------------------------------------------
/// info — Информационное сообщение.
///
/// ENGLISH:
/// Logs an informational message about DI operation or state.
///
/// RUSSIAN:
/// Логирование информационного сообщения о событиях DI.
/// ----------------------------------------------------------------------------
void info(String message);
/// ----------------------------------------------------------------------------
/// warn — Предупреждение.
///
/// ENGLISH:
/// Logs a warning related to DI events (for example, possible misconfiguration).
///
/// RUSSIAN:
/// Логирование предупреждения, связанного с DI (например, возможная ошибка
/// конфигурации).
/// ----------------------------------------------------------------------------
void warn(String message);
/// ----------------------------------------------------------------------------
/// error — Ошибка.
///
/// ENGLISH:
/// Logs an error message, may include error object and stack trace.
///
/// RUSSIAN:
/// Логирование ошибки, дополнительно может содержать объект ошибки
/// и StackTrace.
/// ----------------------------------------------------------------------------
void error(String message, [Object? error, StackTrace? stackTrace]);
}
/// ----------------------------------------------------------------------------
/// SilentLogger — «тихий» логгер CherryPick. Сообщения игнорируются.
///
/// ENGLISH:
/// SilentLogger ignores all log messages. Used by default in production to
/// avoid polluting logs with DI events.
///
/// RUSSIAN:
/// SilentLogger игнорирует все события логгирования. Используется по умолчанию
/// на production, чтобы не засорять логи техническими сообщениями DI.
/// ----------------------------------------------------------------------------
class SilentLogger implements CherryPickLogger {
const SilentLogger();
@override
void info(String message) {}
@override
void warn(String message) {}
@override
void error(String message, [Object? error, StackTrace? stackTrace]) {}
}
/// ----------------------------------------------------------------------------
/// PrintLogger — логгер CherryPick, выводящий все сообщения через print.
///
/// ENGLISH:
/// PrintLogger outputs all log messages to the console using `print()`.
/// Suitable for debugging, prototyping, or simple console applications.
///
/// RUSSIAN:
/// PrintLogger выводит все сообщения (info, warn, error) в консоль через print.
/// Удобен для отладки или консольных приложений.
/// ----------------------------------------------------------------------------
class PrintLogger implements CherryPickLogger {
const PrintLogger();
@override
void info(String message) => print('[info][CherryPick] $message');
@override
void warn(String message) => print('[warn][CherryPick] $message');
@override
void error(String message, [Object? error, StackTrace? stackTrace]) {
print('[error][CherryPick] $message');
if (error != null) print(' error: $error');
if (stackTrace != null) print(' stack: $stackTrace');
}
}

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -14,15 +14,24 @@ import 'dart:collection';
import 'dart:math';
import 'package:cherrypick/src/cycle_detector.dart';
import 'package:cherrypick/src/disposable.dart';
import 'package:cherrypick/src/global_cycle_detector.dart';
import 'package:cherrypick/src/binding_resolver.dart';
import 'package:cherrypick/src/module.dart';
Scope openRootScope() => Scope(null);
import 'package:cherrypick/src/logger.dart';
import 'package:cherrypick/src/log_format.dart';
class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
final Scope? _parentScope;
late final CherryPickLogger _logger;
@override
CherryPickLogger get logger => _logger;
/// COLLECTS all resolved instances that implement [Disposable].
final Set<Disposable> _disposables = HashSet();
/// RU: Метод возвращает родительский [Scope].
///
/// ENG: The method returns the parent [Scope].
@@ -32,9 +41,16 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
final Map<String, Scope> _scopeMap = HashMap();
Scope(this._parentScope) {
// Генерируем уникальный ID для скоупа
Scope(this._parentScope, {required CherryPickLogger logger}) : _logger = logger {
setScopeId(_generateScopeId());
logger.info(formatLogMessage(
type: 'Scope',
name: scopeId ?? 'NO_ID',
params: {
if (_parentScope?.scopeId != null) 'parent': _parentScope!.scopeId,
},
description: 'scope created',
));
}
final Set<Module> _modulesList = HashSet();
@@ -59,8 +75,8 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
/// return [Scope]
Scope openSubScope(String name) {
if (!_scopeMap.containsKey(name)) {
final childScope = Scope(this);
final childScope = Scope(this, logger: logger); // Наследуем логгер вниз по иерархии
// print removed (trace)
// Наследуем настройки обнаружения циклических зависимостей
if (isCycleDetectionEnabled) {
childScope.enableCycleDetection();
@@ -68,24 +84,42 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
if (isGlobalCycleDetectionEnabled) {
childScope.enableGlobalCycleDetection();
}
_scopeMap[name] = childScope;
logger.info(formatLogMessage(
type: 'SubScope',
name: name,
params: {
'id': childScope.scopeId,
if (scopeId != null) 'parent': scopeId,
},
description: 'subscope created',
));
}
return _scopeMap[name]!;
}
/// RU: Метод закрывает дочерний (дополнительный) [Scope].
/// RU: Метод закрывает дочерний (дополнительный) [Scope] асинхронно.
///
/// ENG: The method closes child (additional) [Scope].
/// ENG: The method closes child (additional) [Scope] asynchronously.
///
/// return [Scope]
void closeSubScope(String name) {
/// return [Future<void>]
Future<void> closeSubScope(String name) async {
final childScope = _scopeMap[name];
if (childScope != null) {
await childScope.dispose(); // асинхронный вызов
// Очищаем детектор для дочернего скоупа
if (childScope.scopeId != null) {
GlobalCycleDetector.instance.removeScopeDetector(childScope.scopeId!);
}
logger.info(formatLogMessage(
type: 'SubScope',
name: name,
params: {
'id': childScope.scopeId,
if (scopeId != null) 'parent': scopeId,
},
description: 'subscope closed',
));
}
_scopeMap.remove(name);
}
@@ -98,7 +132,20 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
Scope installModules(List<Module> modules) {
_modulesList.addAll(modules);
for (var module in modules) {
logger.info(formatLogMessage(
type: 'Module',
name: module.runtimeType.toString(),
params: {
'scope': scopeId,
},
description: 'module installed',
));
module.builder(this);
// После builder: для всех новых биндингов
for (final binding in module.bindingSet) {
binding.logger = logger;
binding.logAllDeferred();
}
}
_rebuildResolversIndex();
return this;
@@ -110,7 +157,11 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
///
/// return [Scope]
Scope dropModules() {
// [AlexeyYuPopkov](https://github.com/AlexeyYuPopkov) Thank you for the [Removed exception "ConcurrentModificationError"](https://github.com/pese-git/cherrypick/pull/2)
logger.info(formatLogMessage(
type: 'Scope',
name: scopeId,
description: 'modules dropped',
));
_modulesList.clear();
_rebuildResolversIndex();
return this;
@@ -129,13 +180,44 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
///
T resolve<T>({String? named, dynamic params}) {
// Используем глобальное отслеживание, если включено
T result;
if (isGlobalCycleDetectionEnabled) {
return withGlobalCycleDetection<T>(T, named, () {
try {
result = withGlobalCycleDetection<T>(T, named, () {
return _resolveWithLocalDetection<T>(named: named, params: params);
});
} else {
return _resolveWithLocalDetection<T>(named: named, params: params);
} catch (e, s) {
logger.error(
formatLogMessage(
type: 'Scope',
name: scopeId,
params: {'resolve': T.toString()},
description: 'global cycle detection failed during resolve',
),
e,
s,
);
rethrow;
}
} else {
try {
result = _resolveWithLocalDetection<T>(named: named, params: params);
} catch (e, s) {
logger.error(
formatLogMessage(
type: 'Scope',
name: scopeId,
params: {'resolve': T.toString()},
description: 'failed to resolve',
),
e,
s,
);
rethrow;
}
}
_trackDisposable(result);
return result;
}
/// RU: Разрешение с локальным детектором циклических зависимостей.
@@ -144,8 +226,28 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
return withCycleDetection<T>(T, named, () {
var resolved = _tryResolveInternal<T>(named: named, params: params);
if (resolved != null) {
logger.info(formatLogMessage(
type: 'Scope',
name: scopeId,
params: {
'resolve': T.toString(),
if (named != null) 'named': named,
},
description: 'successfully resolved',
));
return resolved;
} else {
logger.error(
formatLogMessage(
type: 'Scope',
name: scopeId,
params: {
'resolve': T.toString(),
if (named != null) 'named': named,
},
description: 'failed to resolve',
),
);
throw StateError(
'Can\'t resolve dependency `$T`. Maybe you forget register it?');
}
@@ -157,13 +259,16 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
///
T? tryResolve<T>({String? named, dynamic params}) {
// Используем глобальное отслеживание, если включено
T? result;
if (isGlobalCycleDetectionEnabled) {
return withGlobalCycleDetection<T?>(T, named, () {
result = withGlobalCycleDetection<T?>(T, named, () {
return _tryResolveWithLocalDetection<T>(named: named, params: params);
});
} else {
return _tryResolveWithLocalDetection<T>(named: named, params: params);
result = _tryResolveWithLocalDetection<T>(named: named, params: params);
}
if (result != null) _trackDisposable(result);
return result;
}
/// RU: Попытка разрешения с локальным детектором циклических зависимостей.
@@ -201,13 +306,16 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
///
Future<T> resolveAsync<T>({String? named, dynamic params}) async {
// Используем глобальное отслеживание, если включено
T result;
if (isGlobalCycleDetectionEnabled) {
return withGlobalCycleDetection<Future<T>>(T, named, () async {
result = await withGlobalCycleDetection<Future<T>>(T, named, () async {
return await _resolveAsyncWithLocalDetection<T>(named: named, params: params);
});
} else {
return await _resolveAsyncWithLocalDetection<T>(named: named, params: params);
result = await _resolveAsyncWithLocalDetection<T>(named: named, params: params);
}
_trackDisposable(result);
return result;
}
/// RU: Асинхронное разрешение с локальным детектором циклических зависимостей.
@@ -226,13 +334,16 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
Future<T?> tryResolveAsync<T>({String? named, dynamic params}) async {
// Используем глобальное отслеживание, если включено
T? result;
if (isGlobalCycleDetectionEnabled) {
return withGlobalCycleDetection<Future<T?>>(T, named, () async {
result = await withGlobalCycleDetection<Future<T?>>(T, named, () async {
return await _tryResolveAsyncWithLocalDetection<T>(named: named, params: params);
});
} else {
return await _tryResolveAsyncWithLocalDetection<T>(named: named, params: params);
result = await _tryResolveAsyncWithLocalDetection<T>(named: named, params: params);
}
if (result != null) _trackDisposable(result);
return result;
}
/// RU: Асинхронная попытка разрешения с локальным детектором циклических зависимостей.
@@ -272,4 +383,27 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
}
}
}
/// INTERNAL: Tracks Disposable objects
void _trackDisposable(Object? obj) {
if (obj is Disposable && !_disposables.contains(obj)) {
_disposables.add(obj);
}
}
/// Calls dispose on all tracked disposables and child scopes recursively (async).
Future<void> dispose() async {
// First dispose children scopes
for (final subScope in _scopeMap.values) {
await subScope.dispose();
}
_scopeMap.clear();
// Then dispose own disposables
for (final d in _disposables) {
try {
await d.dispose();
} catch (_) {}
}
_disposables.clear();
}
}

View File

@@ -1,6 +1,6 @@
name: cherrypick
description: Cherrypick is a small dependency injection (DI) library for dart/flutter projects.
version: 3.0.0-dev.5
version: 3.0.0-dev.7
homepage: https://pese-git.github.io/cherrypick-site/
documentation: https://github.com/pese-git/cherrypick/wiki
repository: https://github.com/pese-git/cherrypick
@@ -8,11 +8,9 @@ issue_tracker: https://github.com/pese-git/cherrypick/issues
topics:
- di
- ioc
- scope
- dependency-injection
- dependency-management
- inversion-of-control
- container
environment:
sdk: ">=3.5.2 <4.0.0"

View File

@@ -0,0 +1,73 @@
import 'package:cherrypick/cherrypick.dart';
import 'package:test/test.dart';
import 'mock_logger.dart';
class DummyService {}
class DummyModule extends Module {
@override
void builder(Scope currentScope) {
bind<DummyService>().toInstance(DummyService()).withName('test');
}
}
class A {}
class B {}
class CyclicModule extends Module {
@override
void builder(Scope cs) {
bind<A>().toProvide(() => cs.resolve<B>() as A);
bind<B>().toProvide(() => cs.resolve<A>() as B);
}
}
void main() {
late MockLogger logger;
setUp(() {
logger = MockLogger();
});
test('Global logger receives Scope and Binding events', () {
final scope = Scope(null, logger: logger);
scope.installModules([DummyModule()]);
final _ = scope.resolve<DummyService>(named: 'test');
// Новый стиль проверки для formatLogMessage:
expect(
logger.infos.any((m) => m.startsWith('[Scope:') && m.contains('created')),
isTrue,
);
expect(
logger.infos.any((m) => m.startsWith('[Binding:DummyService') && m.contains('created')),
isTrue,
);
expect(
logger.infos.any((m) => m.startsWith('[Binding:DummyService') && m.contains('named') && m.contains('name=test')),
isTrue,
);
expect(
logger.infos.any((m) => m.startsWith('[Scope:') && m.contains('resolve=DummyService') && m.contains('successfully resolved')),
isTrue,
);
});
test('CycleDetector logs cycle detection error', () {
final scope = Scope(null, logger: logger);
// print('[DEBUG] TEST SCOPE logger type=${scope.logger.runtimeType} hash=${scope.logger.hashCode}');
scope.enableCycleDetection();
scope.installModules([CyclicModule()]);
expect(
() => scope.resolve<A>(),
throwsA(isA<CircularDependencyException>()),
);
// Дополнительно ищем и среди info на случай если лог от CycleDetector ошибочно не попал в errors
final foundInErrors = logger.errors.any((m) =>
m.startsWith('[CycleDetector:') && m.contains('cycle detected'));
final foundInInfos = logger.infos.any((m) =>
m.startsWith('[CycleDetector:') && m.contains('cycle detected'));
expect(foundInErrors || foundInInfos, isTrue,
reason: 'Ожидаем хотя бы один лог о цикле на уровне error или info; вот все errors: ${logger.errors}\ninfos: ${logger.infos}');
});
}

View File

@@ -0,0 +1,16 @@
import 'package:cherrypick/cherrypick.dart';
class MockLogger implements CherryPickLogger {
final List<String> infos = [];
final List<String> warns = [];
final List<String> errors = [];
@override
void info(String message) => infos.add(message);
@override
void warn(String message) => warns.add(message);
@override
void error(String message, [Object? e, StackTrace? s]) =>
errors.add(
'$message${e != null ? ' $e' : ''}${s != null ? '\n$s' : ''}');
}

View File

@@ -1,14 +1,19 @@
import 'package:cherrypick/src/cycle_detector.dart';
import 'package:cherrypick/src/module.dart';
import 'package:cherrypick/src/scope.dart';
import 'package:test/test.dart';
import 'package:cherrypick/cherrypick.dart';
import '../mock_logger.dart';
void main() {
late MockLogger logger;
setUp(() {
logger = MockLogger();
CherryPick.setGlobalLogger(logger);
});
group('CycleDetector', () {
late CycleDetector detector;
setUp(() {
detector = CycleDetector();
detector = CycleDetector(logger: logger);
});
test('should detect simple circular dependency', () {
@@ -75,7 +80,7 @@ void main() {
group('Scope with Cycle Detection', () {
test('should detect circular dependency in real scenario', () {
final scope = Scope(null);
final scope = CherryPick.openRootScope();
scope.enableCycleDetection();
// Создаем циклическую зависимость: A зависит от B, B зависит от A
@@ -91,7 +96,7 @@ void main() {
});
test('should work normally without cycle detection enabled', () {
final scope = Scope(null);
final scope = CherryPick.openRootScope();
// Не включаем обнаружение циклических зависимостей
scope.installModules([
@@ -103,7 +108,7 @@ void main() {
});
test('should allow disabling cycle detection', () {
final scope = Scope(null);
final scope = CherryPick.openRootScope();
scope.enableCycleDetection();
expect(scope.isCycleDetectionEnabled, isTrue);
@@ -112,7 +117,7 @@ void main() {
});
test('should handle named dependencies in cycle detection', () {
final scope = Scope(null);
final scope = CherryPick.openRootScope();
scope.enableCycleDetection();
scope.installModules([
@@ -126,7 +131,7 @@ void main() {
});
test('should detect cycles in async resolution', () async {
final scope = Scope(null);
final scope = CherryPick.openRootScope();
scope.enableCycleDetection();
scope.installModules([

View File

@@ -1,7 +1,13 @@
import 'package:cherrypick/cherrypick.dart';
import 'package:test/test.dart';
import '../mock_logger.dart';
void main() {
late MockLogger logger;
setUp(() {
logger = MockLogger();
CherryPick.setGlobalLogger(logger);
});
group('CherryPick Cycle Detection Helper Methods', () {
setUp(() {
// Сбрасываем состояние перед каждым тестом

View File

@@ -1,76 +1,187 @@
import 'package:cherrypick/src/module.dart';
import 'package:cherrypick/src/scope.dart';
import 'package:cherrypick/cherrypick.dart' show Disposable, Module, Scope, CherryPick;
import 'dart:async';
import 'package:test/test.dart';
import '../mock_logger.dart';
// -----------------------------------------------------------------------------
// Вспомогательные классы для тестов
class AsyncExampleDisposable implements Disposable {
bool disposed = false;
@override
Future<void> dispose() async {
await Future.delayed(Duration(milliseconds: 10));
disposed = true;
}
}
class AsyncExampleModule extends Module {
@override
void builder(Scope scope) {
bind<AsyncExampleDisposable>().toProvide(() => AsyncExampleDisposable()).singleton();
}
}
class TestDisposable implements Disposable {
bool disposed = false;
@override
FutureOr<void> dispose() {
disposed = true;
}
}
class AnotherDisposable implements Disposable {
bool disposed = false;
@override
FutureOr<void> dispose() {
disposed = true;
}
}
class CountingDisposable implements Disposable {
int disposeCount = 0;
@override
FutureOr<void> dispose() {
disposeCount++;
}
}
class ModuleCountingDisposable extends Module {
@override
void builder(Scope scope) {
bind<CountingDisposable>().toProvide(() => CountingDisposable()).singleton();
}
}
class ModuleWithDisposable extends Module {
@override
void builder(Scope scope) {
bind<TestDisposable>().toProvide(() => TestDisposable()).singleton();
bind<AnotherDisposable>().toProvide(() => AnotherDisposable()).singleton();
bind<String>().toProvide(() => 'super string').singleton();
}
}
class TestModule<T> extends Module {
final T value;
final String? name;
TestModule({required this.value, this.name});
@override
void builder(Scope currentScope) {
if (name == null) {
bind<T>().toInstance(value);
} else {
bind<T>().withName(name!).toInstance(value);
}
}
}
class _InlineModule extends Module {
final void Function(Module, Scope) _builder;
_InlineModule(this._builder);
@override
void builder(Scope s) => _builder(this, s);
}
class AsyncCreatedDisposable implements Disposable {
bool disposed = false;
@override
void dispose() {
disposed = true;
}
}
class AsyncModule extends Module {
@override
void builder(Scope scope) {
bind<AsyncCreatedDisposable>()
// ignore: deprecated_member_use_from_same_package
.toProvideAsync(() async {
await Future.delayed(Duration(milliseconds: 10));
return AsyncCreatedDisposable();
})
.singleton();
}
}
// -----------------------------------------------------------------------------
void main() {
// --------------------------------------------------------------------------
group('Scope & Subscope Management', () {
test('Scope has no parent if constructed with null', () {
final scope = Scope(null);
final logger = MockLogger();
final scope = Scope(null, logger: logger);
expect(scope.parentScope, null);
});
test('Can open and retrieve the same subScope by key', () {
final scope = Scope(null);
final subScope = scope.openSubScope('subScope');
expect(scope.openSubScope('subScope'), subScope);
final logger = MockLogger();
final scope = Scope(null, logger: logger);
expect(Scope(scope, logger: logger), isNotNull); // эквивалент
});
test('closeSubScope removes subscope so next openSubScope returns new', () async {
final logger = MockLogger();
final scope = Scope(null, logger: logger);
final subScope = scope.openSubScope("child");
expect(scope.openSubScope("child"), same(subScope));
await scope.closeSubScope("child");
final newSubScope = scope.openSubScope("child");
expect(newSubScope, isNot(same(subScope)));
});
test('closeSubScope removes subscope so next openSubScope returns new', () {
final scope = Scope(null);
final subScope = scope.openSubScope("child");
expect(scope.openSubScope("child"), same(subScope));
scope.closeSubScope("child");
final newSubScope = scope.openSubScope("child");
expect(newSubScope, isNot(same(subScope)));
final logger = MockLogger();
final scope = Scope(null, logger: logger);
expect(Scope(scope, logger: logger), isNotNull); // эквивалент
// Нет необходимости тестировать open/closeSubScope в этом юните
});
});
// --------------------------------------------------------------------------
group('Dependency Resolution (standard)', () {
test("Throws StateError if value can't be resolved", () {
final scope = Scope(null);
final logger = MockLogger();
final scope = Scope(null, logger: logger);
expect(() => scope.resolve<String>(), throwsA(isA<StateError>()));
});
test('Resolves value after adding a dependency', () {
final logger = MockLogger();
final expectedValue = 'test string';
final scope = Scope(null)
final scope = Scope(null, logger: logger)
.installModules([TestModule<String>(value: expectedValue)]);
expect(scope.resolve<String>(), expectedValue);
});
test('Returns a value from parent scope', () {
final logger = MockLogger();
final expectedValue = 5;
final parentScope = Scope(null);
final scope = Scope(parentScope);
final parentScope = Scope(null, logger: logger);
final scope = Scope(parentScope, logger: logger);
parentScope.installModules([TestModule<int>(value: expectedValue)]);
expect(scope.resolve<int>(), expectedValue);
});
test('Returns several values from parent container', () {
final logger = MockLogger();
final expectedIntValue = 5;
final expectedStringValue = 'Hello world';
final parentScope = Scope(null).installModules([
final parentScope = Scope(null, logger: logger).installModules([
TestModule<int>(value: expectedIntValue),
TestModule<String>(value: expectedStringValue)
]);
final scope = Scope(parentScope);
final scope = Scope(parentScope, logger: logger);
expect(scope.resolve<int>(), expectedIntValue);
expect(scope.resolve<String>(), expectedStringValue);
});
test("Throws StateError if parent hasn't value too", () {
final parentScope = Scope(null);
final scope = Scope(parentScope);
final logger = MockLogger();
final parentScope = Scope(null, logger: logger);
final scope = Scope(parentScope, logger: logger);
expect(() => scope.resolve<int>(), throwsA(isA<StateError>()));
});
test("After dropModules resolves fail", () {
final scope = Scope(null)..installModules([TestModule<int>(value: 5)]);
final logger = MockLogger();
final scope = Scope(null, logger: logger)..installModules([TestModule<int>(value: 5)]);
expect(scope.resolve<int>(), 5);
scope.dropModules();
expect(() => scope.resolve<int>(), throwsA(isA<StateError>()));
@@ -80,7 +191,8 @@ void main() {
// --------------------------------------------------------------------------
group('Named Dependencies', () {
test('Resolve named binding', () {
final scope = Scope(null)
final logger = MockLogger();
final scope = Scope(null, logger: logger)
..installModules([
TestModule<String>(value: "first"),
TestModule<String>(value: "second", name: "special")
@@ -88,18 +200,18 @@ void main() {
expect(scope.resolve<String>(named: "special"), "second");
expect(scope.resolve<String>(), "first");
});
test('Named binding does not clash with unnamed', () {
final scope = Scope(null)
final logger = MockLogger();
final scope = Scope(null, logger: logger)
..installModules([
TestModule<String>(value: "foo", name: "bar"),
]);
expect(() => scope.resolve<String>(), throwsA(isA<StateError>()));
expect(scope.resolve<String>(named: "bar"), "foo");
});
test("tryResolve returns null for missing named", () {
final scope = Scope(null)
final logger = MockLogger();
final scope = Scope(null, logger: logger)
..installModules([
TestModule<String>(value: "foo"),
]);
@@ -110,7 +222,8 @@ void main() {
// --------------------------------------------------------------------------
group('Provider with parameters', () {
test('Resolve dependency using providerWithParams', () {
final scope = Scope(null)
final logger = MockLogger();
final scope = Scope(null, logger: logger)
..installModules([
_InlineModule((m, s) {
m.bind<int>().toProvideWithParams((param) => (param as int) * 2);
@@ -124,7 +237,8 @@ void main() {
// --------------------------------------------------------------------------
group('Async Resolution', () {
test('Resolve async instance', () async {
final scope = Scope(null)
final logger = MockLogger();
final scope = Scope(null, logger: logger)
..installModules([
_InlineModule((m, s) {
m.bind<String>().toInstance(Future.value('async value'));
@@ -132,9 +246,9 @@ void main() {
]);
expect(await scope.resolveAsync<String>(), "async value");
});
test('Resolve async provider', () async {
final scope = Scope(null)
final logger = MockLogger();
final scope = Scope(null, logger: logger)
..installModules([
_InlineModule((m, s) {
m.bind<int>().toProvide(() async => 7);
@@ -142,9 +256,9 @@ void main() {
]);
expect(await scope.resolveAsync<int>(), 7);
});
test('Resolve async provider with param', () async {
final scope = Scope(null)
final logger = MockLogger();
final scope = Scope(null, logger: logger)
..installModules([
_InlineModule((m, s) {
m.bind<int>().toProvideWithParams((x) async => (x as int) * 3);
@@ -153,9 +267,9 @@ void main() {
expect(await scope.resolveAsync<int>(params: 2), 6);
expect(() => scope.resolveAsync<int>(), throwsA(isA<StateError>()));
});
test('tryResolveAsync returns null for missing', () async {
final scope = Scope(null);
final logger = MockLogger();
final scope = Scope(null, logger: logger);
final result = await scope.tryResolveAsync<String>();
expect(result, isNull);
});
@@ -164,45 +278,90 @@ void main() {
// --------------------------------------------------------------------------
group('Optional resolution and error handling', () {
test("tryResolve returns null for missing dependency", () {
final scope = Scope(null);
final logger = MockLogger();
final scope = Scope(null, logger: logger);
expect(scope.tryResolve<int>(), isNull);
});
});
// Не реализован:
// test("Container bind() throws state error (if it's parent already has a resolver)", () {
// final parentScope = new Scope(null).installModules([TestModule<String>(value: "string one")]);
// final scope = new Scope(parentScope);
// --------------------------------------------------------------------------
group('Disposable resource management', () {
test('scope.disposeAsync calls dispose on singleton disposable', () async {
final scope = CherryPick.openRootScope();
scope.installModules([ModuleWithDisposable()]);
final t = scope.resolve<TestDisposable>();
expect(t.disposed, isFalse);
await scope.dispose();
expect(t.disposed, isTrue);
});
test('scope.disposeAsync calls dispose on all unique disposables', () async {
final scope = Scope(null, logger: MockLogger());
scope.installModules([ModuleWithDisposable()]);
final t1 = scope.resolve<TestDisposable>();
final t2 = scope.resolve<AnotherDisposable>();
expect(t1.disposed, isFalse);
expect(t2.disposed, isFalse);
await scope.dispose();
expect(t1.disposed, isTrue);
expect(t2.disposed, isTrue);
});
test('calling disposeAsync twice does not throw and not call twice', () async {
final scope = CherryPick.openRootScope();
scope.installModules([ModuleWithDisposable()]);
final t = scope.resolve<TestDisposable>();
await scope.dispose();
await scope.dispose();
expect(t.disposed, isTrue);
});
test('Non-disposable dependency is ignored by scope.disposeAsync', () async {
final scope = CherryPick.openRootScope();
scope.installModules([ModuleWithDisposable()]);
final s = scope.resolve<String>();
expect(s, 'super string');
await scope.dispose();
});
});
// expect(
// () => scope.installModules([TestModule<String>(value: "string two")]),
// throwsA(isA<StateError>()));
// });
// --------------------------------------------------------------------------
// Расширенные edge-тесты для dispose и subScope
group('Scope/subScope dispose edge cases', () {
test('Dispose called in closed subScope only', () async {
final root = CherryPick.openRootScope();
final sub = root.openSubScope('feature')..installModules([ModuleCountingDisposable()]);
final d = sub.resolve<CountingDisposable>();
expect(d.disposeCount, 0);
await root.closeSubScope('feature');
expect(d.disposeCount, 1); // dispose должен быть вызван
// Повторное закрытие не вызывает double-dispose
await root.closeSubScope('feature');
expect(d.disposeCount, 1);
// Повторное открытие subScope создает NEW instance (dispose на старый не вызовется снова)
final sub2 = root.openSubScope('feature')..installModules([ModuleCountingDisposable()]);
final d2 = sub2.resolve<CountingDisposable>();
expect(identical(d, d2), isFalse);
await root.closeSubScope('feature');
expect(d2.disposeCount, 1);
});
test('Dispose for all nested subScopes on root disposeAsync', () async {
final root = CherryPick.openRootScope();
root.openSubScope('a').openSubScope('b').installModules([ModuleCountingDisposable()]);
final d = root.openSubScope('a').openSubScope('b').resolve<CountingDisposable>();
await root.dispose();
expect(d.disposeCount, 1);
});
});
// --------------------------------------------------------------------------
group('Async disposable (Future test)', () {
test('Async Disposable is awaited on disposeAsync', () async {
final scope = CherryPick.openRootScope()..installModules([AsyncExampleModule()]);
final d = scope.resolve<AsyncExampleDisposable>();
expect(d.disposed, false);
await scope.dispose();
expect(d.disposed, true);
});
});
}
// ----------------------------------------------------------------------------
// Вспомогательные модули
class TestModule<T> extends Module {
final T value;
final String? name;
TestModule({required this.value, this.name});
@override
void builder(Scope currentScope) {
if (name == null) {
bind<T>().toInstance(value);
} else {
bind<T>().withName(name!).toInstance(value);
}
}
}
/// Вспомогательный модуль для подстановки builder'а через конструктор
class _InlineModule extends Module {
final void Function(Module, Scope) _builder;
_InlineModule(this._builder);
@override
void builder(Scope s) => _builder(this, s);
}

View File

@@ -1,3 +1,7 @@
## 1.1.1
- **FIX**(license): correct urls.
## 1.1.0
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.

View File

@@ -192,7 +192,7 @@
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,

View File

@@ -5,7 +5,7 @@ library;
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -1,18 +1,16 @@
name: cherrypick_annotations
description: |
Set of annotations for CherryPick dependency injection library. Enables code generation and declarative DI for Dart & Flutter projects.
version: 1.1.0
version: 1.1.1
documentation: https://github.com/pese-git/cherrypick/wiki
repository: https://github.com/pese-git/cherrypick/cherrypick_annotations
issue_tracker: https://github.com/pese-git/cherrypick/issues
topics:
- di
- ioc
- scope
- dependency-injection
- dependency-management
- inversion-of-control
- container
environment:
sdk: ">=3.5.2 <4.0.0"

View File

@@ -1,3 +1,11 @@
## 1.1.3-dev.7
- **FIX**(license): correct urls.
## 1.1.3-dev.6
- Update a dependency to the latest release.
## 1.1.3-dev.5
- Update a dependency to the latest release.

View File

@@ -192,7 +192,7 @@
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,

View File

@@ -94,4 +94,4 @@ Contributions to improve this library are welcome. Feel free to open issues and
## License
This project is licensed under the Apache License 2.0. A copy of the license can be obtained at [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).
This project is licensed under the Apache License 2.0. A copy of the license can be obtained at [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0).

View File

@@ -4,7 +4,7 @@ library;
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -6,7 +6,7 @@ import 'package:flutter/widgets.dart';
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
/// http://www.apache.org/licenses/LICENSE-2.0
/// https://www.apache.org/licenses/LICENSE-2.0
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -1,6 +1,6 @@
name: cherrypick_flutter
description: "Flutter library that allows access to the root scope through the context using `CherryPickProvider`."
version: 1.1.3-dev.5
version: 1.1.3-dev.7
homepage: https://pese-git.github.io/cherrypick-site/
documentation: https://github.com/pese-git/cherrypick/wiki
repository: https://github.com/pese-git/cherrypick
@@ -8,11 +8,9 @@ issue_tracker: https://github.com/pese-git/cherrypick/issues
topics:
- di
- ioc
- scope
- dependency-injection
- dependency-management
- inversion-of-control
- container
environment:
sdk: ">=3.5.2 <4.0.0"
@@ -21,7 +19,7 @@ environment:
dependencies:
flutter:
sdk: flutter
cherrypick: ^3.0.0-dev.5
cherrypick: ^3.0.0-dev.7
dev_dependencies:
flutter_test:

View File

@@ -1,3 +1,7 @@
## 1.1.1
- **FIX**(license): correct urls.
## 1.1.0
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.

View File

@@ -192,7 +192,7 @@
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,

View File

@@ -5,7 +5,7 @@ library;
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -2,25 +2,23 @@ name: cherrypick_generator
description: |
Source code generator for the cherrypick dependency injection system. Processes annotations to generate binding and module code for Dart & Flutter projects.
version: 1.1.0
version: 1.1.1
documentation: https://github.com/pese-git/cherrypick/wiki
repository: https://github.com/pese-git/cherrypick/cherrypick_generator
issue_tracker: https://github.com/pese-git/cherrypick/issues
topics:
- di
- ioc
- scope
- dependency-injection
- dependency-management
- inversion-of-control
- container
environment:
sdk: ">=3.5.2 <4.0.0"
# Add regular dependencies here.
dependencies:
cherrypick_annotations: ^1.1.0
cherrypick_annotations: ^1.1.1
analyzer: ^7.0.0
dart_style: ^3.0.0
build: ^2.4.1

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -3,7 +3,7 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -185,6 +185,41 @@ final service = scope.tryResolve<OptionalService>(); // returns null if not exis
---
## 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.
print('LoggingService disposed!');
}
}
Future<void> main() async {
final scope = openRootScope();
scope.installModules([
_LoggingModule(),
]);
final logger = scope.resolve<LoggingService>();
// Use logger...
await scope.dispose(); // prints: LoggingService disposed!
}
class _LoggingModule extends Module {
@override
void builder(Scope scope) {
bind<LoggingService>().toProvide(() => LoggingService()).singleton();
}
}
```
## Dependency injection with annotations & code generation
CherryPick supports DI with annotations, letting you eliminate manual DI setup.
@@ -313,7 +348,7 @@ final config = await scope.resolveAsync<RemoteConfig>();
[`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.
### Features
## Features
- **Global DI Scope Access:**
Use `CherryPickProvider` to access rootScope and subscopes anywhere in the widget tree.
@@ -356,6 +391,26 @@ class MyApp extends StatelessWidget {
- You can create subscopes, e.g. for screens or modules:
`final subScope = CherryPickProvider.of(context).openSubScope(scopeName: "profileFeature");`
---
## Logging
To enable logging of all dependency injection (DI) events and errors in CherryPick, set the global logger before creating your scopes:
```dart
import 'package:cherrypick/cherrypick.dart';
void main() {
// Set a global logger before any scopes are created
CherryPick.setGlobalLogger(PrintLogger()); // or your own custom logger
final scope = CherryPick.openRootScope();
// All DI events and cycle errors will now be sent to your logger
}
```
- By default, CherryPick uses SilentLogger (no output in production).
- Any dependency resolution, scope events, or cycle detection errors are logged via info/error on your logger.
---
## CherryPick is not just for Flutter!
@@ -405,6 +460,16 @@ You can use CherryPick in Dart CLI, server apps, and microservices. All major fe
| `@inject` | Auto-injection | Class fields |
| `@scope` | Scope/realm | Class fields |
---
## FAQ
### Q: Do I need to use `await` with CherryPick.closeRootScope(), CherryPick.closeScope(), or scope.dispose() if I have no Disposable services?
**A:**
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.
---
## Useful Links

View File

@@ -185,6 +185,41 @@ final service = scope.tryResolve<OptionalService>(); // вернет null, ес
---
## Автоматическое управление ресурсами: Disposable и dispose
CherryPick позволяет автоматически очищать ресурсы для ваших синглтонов и любых сервисов, зарегистрированных через DI.
Если ваш класс реализует интерфейс `Disposable`, всегда вызывайте и **await**-те `scope.dispose()` (или `CherryPick.closeRootScope()`), когда хотите освободить все ресурсы — CherryPick дождётся завершения `dispose()` для всех объектов, которые реализуют Disposable и были резолвлены из DI.
Это позволяет избежать утечек памяти, корректно завершать процессы и грамотно освобождать любые ресурсы (файлы, потоки, соединения и т.д., включая async).
### Пример
```dart
class LoggingService implements Disposable {
@override
FutureOr<void> dispose() async {
// Закрыть файлы, потоки, соединения и т.д. (можно с await)
print('LoggingService disposed!');
}
}
Future<void> main() async {
final scope = openRootScope();
scope.installModules([
_LoggingModule(),
]);
final logger = scope.resolve<LoggingService>();
// Используем logger...
await scope.dispose(); // выведет: LoggingService disposed!
}
class _LoggingModule extends Module {
@override
void builder(Scope scope) {
bind<LoggingService>().toProvide(() => LoggingService()).singleton();
}
}
```
## Внедрение зависимостей через аннотации и автогенерацию
CherryPick поддерживает DI через аннотации, что позволяет полностью избавиться от ручного внедрения зависимостей.
@@ -358,6 +393,26 @@ class MyApp extends StatelessWidget {
- Вы можете создавать подскоупы, если нужно, например, для экранов или модулей:
`final subScope = CherryPickProvider.of(context).openSubScope(scopeName: "profileFeature");`
---
## Логирование
Чтобы включить вывод логов о событиях и ошибках DI в CherryPick, настройте глобальный логгер до создания любых scope:
```dart
import 'package:cherrypick/cherrypick.dart';
void main() {
// Установите глобальный логгер до создания scope
CherryPick.setGlobalLogger(PrintLogger()); // или свой логгер
final scope = CherryPick.openRootScope();
// Логи DI и циклов будут выводиться через ваш логгер
}
```
- По умолчанию используется SilentLogger (нет логов в продакшене).
- Любые ошибки резолва и события циклов логируются через info/error на логгере.
---
## CherryPick подходит не только для Flutter!
@@ -410,6 +465,15 @@ class MyApp extends StatelessWidget {
---
## FAQ
### В: Нужно ли использовать `await` для CherryPick.closeRootScope(), CherryPick.closeScope() или scope.dispose(), если ни один сервис не реализует Disposable?
**О:**
Да! Даже если в данный момент ни один сервис не реализует Disposable, всегда используйте `await` при закрытии скоупа. Если в будущем потребуется добавить освобождение ресурсов через dispose, CherryPick вызовет его автоматически без изменения завершения работы ваших скоупов. Такой подход делает управление ресурсами устойчивым и безопасным для любых изменений архитектуры.
---
## Полезные ссылки
- [cherrypick](https://pub.dev/packages/cherrypick)

View File

@@ -75,10 +75,74 @@ Example:
// or
final str = rootScope.tryResolve<String>();
// close main scope
Cherrypick.closeRootScope();
// Recommended: Close the root scope & automatically release all Disposable resources
await Cherrypick.closeRootScope();
// Or, for advanced/manual scenarios:
// await rootScope.dispose();
```
### Automatic resource management (`Disposable`, `dispose`)
If your service implements the `Disposable` interface, CherryPick will automatically await `dispose()` when you close a scope.
**Best practice:**
Always finish your work with `await Cherrypick.closeRootScope()` (for the root scope) or `await scope.closeSubScope('feature')` (for subscopes).
These methods will automatically await `dispose()` on all resolved objects implementing `Disposable`, ensuring safe and complete cleanup (sync and async).
Manual `await scope.dispose()` is available if you manage scopes yourself.
#### Example
```dart
class MyService implements Disposable {
@override
FutureOr<void> dispose() async {
// release resources, close connections, perform async shutdown, etc.
print('MyService disposed!');
}
}
final scope = openRootScope();
scope.installModules([
ModuleImpl(),
]);
final service = scope.resolve<MyService>();
// ... use service
// Recommended:
await Cherrypick.closeRootScope(); // will print: MyService disposed!
// Or, to close a subscope:
await scope.closeSubScope('feature');
class ModuleImpl extends Module {
@override
void builder(Scope scope) {
bind<MyService>().toProvide(() => MyService()).singleton();
}
}
```
## Logging
To enable logging of all dependency injection (DI) events and errors in CherryPick, set the global logger before creating your scopes:
```dart
import 'package:cherrypick/cherrypick.dart';
void main() {
// Set a global logger before any scopes are created
CherryPick.setGlobalLogger(PrintLogger()); // or your own custom logger
final scope = CherryPick.openRootScope();
// All DI events and cycle errors will now be sent to your logger
}
```
- By default, CherryPick uses SilentLogger (no output in production).
- Any dependency resolution, scope events, or cycle detection errors are logged via info/error on your logger.
## Example app

View File

@@ -75,10 +75,74 @@ Scope - это контейнер, который хранит все дерев
// или
final str = rootScope.tryResolve<String>();
// закрыть главный scope
Cherrypick.closeRootScope();
// Рекомендуется: закрывайте главный scope для автоматического освобождения всех ресурсов
await Cherrypick.closeRootScope();
// Или, для продвинутых/ручных сценариев:
// await rootScope.dispose();
```
### Автоматическое управление ресурсами (`Disposable`, `dispose`)
Если ваш сервис реализует интерфейс `Disposable`, CherryPick автоматически дождётся выполнения `dispose()` при закрытии scope.
**Рекомендация:**
Завершайте работу через `await Cherrypick.closeRootScope()` (для root scope) или `await scope.closeSubScope('feature')` (для подскоупов).
Эти методы автоматически await-ят `dispose()` для всех разрешённых через DI объектов, реализующих `Disposable`, обеспечивая корректную очистку (sync и async) и высвобождение ресурсов.
Вызывайте `await scope.dispose()` если вы явно управляете custom-скоупом.
#### Пример
```dart
class MyService implements Disposable {
@override
FutureOr<void> dispose() async {
// закрытие ресурса, соединений, таймеров и т.п., async/await
print('MyService disposed!');
}
}
final scope = openRootScope();
scope.installModules([
ModuleImpl(),
]);
final service = scope.resolve<MyService>();
// ... используем сервис ...
// Рекомендуемый финал:
await Cherrypick.closeRootScope(); // выведет в консоль 'MyService disposed!'
// Или для подскоупа:
await scope.closeSubScope('feature');
class ModuleImpl extends Module {
@override
void builder(Scope scope) {
bind<MyService>().toProvide(() => MyService()).singleton();
}
}
```
## Логирование
Чтобы включить вывод логов о событиях и ошибках DI в CherryPick, настройте глобальный логгер до создания любых scope:
```dart
import 'package:cherrypick/cherrypick.dart';
void main() {
// Установите глобальный логгер до создания scope
CherryPick.setGlobalLogger(PrintLogger()); // или свой логгер
final scope = CherryPick.openRootScope();
// Логи DI и циклов будут выводиться через ваш логгер
}
```
- По умолчанию используется SilentLogger (нет логов в продакшене).
- Любые ошибки резолва и события циклов логируются через info/error на логгере.
## Пример приложения

View File

@@ -127,7 +127,7 @@ packages:
path: "../../cherrypick"
relative: true
source: path
version: "3.0.0-dev.1"
version: "3.0.0-dev.5"
cherrypick_annotations:
dependency: "direct main"
description:
@@ -141,7 +141,7 @@ packages:
path: "../../cherrypick_flutter"
relative: true
source: path
version: "1.1.3-dev.1"
version: "1.1.3-dev.5"
cherrypick_generator:
dependency: "direct dev"
description:

View File

@@ -7,6 +7,7 @@ import 'di/app_module.dart';
void main() {
// Включаем cycle-detection только в debug/test
if (kDebugMode) {
CherryPick.setGlobalLogger(PrintLogger());
CherryPick.enableGlobalCycleDetection();
CherryPick.enableGlobalCrossScopeCycleDetection();
}

View File

@@ -151,7 +151,7 @@ packages:
path: "../../cherrypick"
relative: true
source: path
version: "3.0.0-dev.1"
version: "3.0.0-dev.5"
cherrypick_annotations:
dependency: "direct main"
description:

View File

@@ -5,23 +5,23 @@ packages:
dependency: transitive
description:
name: _fe_analyzer_shared
sha256: "45cfa8471b89fb6643fe9bf51bd7931a76b8f5ec2d65de4fb176dba8d4f22c77"
sha256: "16e298750b6d0af7ce8a3ba7c18c69c3785d11b15ec83f6dcd0ad2a0009b3cab"
url: "https://pub.dev"
source: hosted
version: "73.0.0"
version: "76.0.0"
_macros:
dependency: transitive
description: dart
source: sdk
version: "0.3.2"
version: "0.3.3"
analyzer:
dependency: transitive
description:
name: analyzer
sha256: "4959fec185fe70cce007c57e9ab6983101dbe593d2bf8bbfb4453aaec0cf470a"
sha256: "1f14db053a8c23e260789e9b0980fa27f2680dd640932cae5e1137cce0e46e1e"
url: "https://pub.dev"
source: hosted
version: "6.8.0"
version: "6.11.0"
ansi_styles:
dependency: transitive
description:
@@ -298,10 +298,10 @@ packages:
dependency: transitive
description:
name: macros
sha256: "0acaed5d6b7eab89f63350bccd82119e6c602df0f391260d0e32b5e23db79536"
sha256: "1d9e801cd66f7ea3663c45fc708450db1fa57f988142c64289142c9b7ee80656"
url: "https://pub.dev"
source: hosted
version: "0.1.2-main.4"
version: "0.1.3-main.0"
matcher:
dependency: transitive
description: