mirror of
https://github.com/pese-git/cherrypick.git
synced 2026-01-24 13:47:24 +00:00
Compare commits
5 Commits
cherrypick
...
cherrypick
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
58daf668c5 | ||
|
|
b57ca797e1 | ||
|
|
38fd356ec3 | ||
|
|
8fd18df811 | ||
|
|
06c0dd60c0 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -18,7 +18,5 @@ pubspec_overrides.yaml
|
||||
melos_cherrypick.iml
|
||||
melos_cherrypick_workspace.iml
|
||||
melos_cherrypick_flutter.iml
|
||||
melos_benchmark_di.iml
|
||||
melos_talker_cherrypick_logger.iml
|
||||
|
||||
coverage
|
||||
262
CHANGELOG.md
262
CHANGELOG.md
@@ -3,268 +3,6 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
## 2025-08-12
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.8`](#cherrypick---v300-dev8)
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.8`](#cherrypick_flutter---v113-dev8)
|
||||
|
||||
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.8`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.8`
|
||||
|
||||
- **REFACTOR**(tests): replace MockLogger with MockObserver in scope tests to align with updated observer API.
|
||||
- **FIX**(doc): remove hide symbol.
|
||||
- **FEAT**(core): add full DI lifecycle observability via onInstanceDisposed.
|
||||
- **DOCS**(logging): update Logging section in README with modern Observer usage and Talker integration examples.
|
||||
- **DOCS**(observer): improve documentation, translate all comments to English, add usage examples.
|
||||
- **DOCS**(README): add section with overview table for additional modules.
|
||||
- **DOCS**(README): refactor structure and improve clarity of advanced features.
|
||||
- **DOCS**(README): add 'Hierarchical Subscopes' section and update structure for advanced features clarity.
|
||||
|
||||
|
||||
## 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
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.5`](#cherrypick---v300-dev5)
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.5`](#cherrypick_flutter---v113-dev5)
|
||||
|
||||
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.5`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.5`
|
||||
|
||||
- **REFACTOR**(scope): simplify _findBindingResolver<T> with one-liner and optional chaining.
|
||||
- **PERF**(scope): speed up dependency lookup with Map-based binding resolver index.
|
||||
- **DOCS**(perf): clarify Map-based resolver optimization applies since v3.0.0 in all docs.
|
||||
- **DOCS**: update EN/RU quick start and tutorial with Fast Map-based lookup section; clarify performance benefit in README.
|
||||
|
||||
|
||||
## 2025-08-07
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.4`](#cherrypick---v300-dev4)
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.4`](#cherrypick_flutter---v113-dev4)
|
||||
|
||||
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.4`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.4`
|
||||
|
||||
- **REFACTOR**(scope): simplify _findBindingResolver<T> with one-liner and optional chaining.
|
||||
- **PERF**(scope): speed up dependency lookup with Map-based binding resolver index.
|
||||
- **DOCS**(perf): clarify Map-based resolver optimization applies since v3.0.0 in all docs.
|
||||
- **DOCS**: update EN/RU quick start and tutorial with Fast Map-based lookup section; clarify performance benefit in README.
|
||||
|
||||
|
||||
## 2025-08-07
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.3`](#cherrypick---v300-dev3)
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.3`](#cherrypick_flutter---v113-dev3)
|
||||
|
||||
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.3`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.3`
|
||||
|
||||
- **REFACTOR**(scope): simplify _findBindingResolver<T> with one-liner and optional chaining.
|
||||
- **PERF**(scope): speed up dependency lookup with Map-based binding resolver index.
|
||||
- **DOCS**(perf): clarify Map-based resolver optimization applies since v3.0.0 in all docs.
|
||||
- **DOCS**: update EN/RU quick start and tutorial with Fast Map-based lookup section; clarify performance benefit in README.
|
||||
|
||||
|
||||
## 2025-08-04
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.2`](#cherrypick---v300-dev2)
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.2`](#cherrypick_flutter---v113-dev2)
|
||||
|
||||
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.2`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.2`
|
||||
|
||||
- **FEAT**(binding): add deprecated proxy async methods for backward compatibility and highlight transition to modern API.
|
||||
- **DOCS**: add quick guide for circular dependency detection to README.
|
||||
- **DOCS**: add quick guide for circular dependency detection to README.
|
||||
- **BREAKING** **FEAT**: implement comprehensive circular dependency detection system.
|
||||
- **BREAKING** **FEAT**: implement comprehensive circular dependency detection system.
|
||||
|
||||
|
||||
## 2025-07-30
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.1`](#cherrypick---v300-dev1)
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.1`](#cherrypick_flutter---v113-dev1)
|
||||
|
||||
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.1`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.1`
|
||||
|
||||
- **DOCS**: add quick guide for circular dependency detection to README.
|
||||
|
||||
|
||||
## 2025-07-30
|
||||
|
||||
### Changes
|
||||
|
||||
2
LICENSE
2
LICENSE
@@ -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
|
||||
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
http://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,
|
||||
|
||||
@@ -1,275 +0,0 @@
|
||||
# benchmark_di
|
||||
|
||||
_Benchmark suite for cherrypick DI container, get_it, and other DI solutions._
|
||||
|
||||
## Overview
|
||||
|
||||
benchmark_di is a flexible benchmarking suite to compare DI containers (like cherrypick and get_it) on synthetic, deep, and real-world dependency scenarios – chains, factories, async, named, override, etc.
|
||||
|
||||
**Features:**
|
||||
- Universal registration layer and modular scenario setup (works with any DI)
|
||||
- Built-in support for [cherrypick](https://github.com/) and [get_it](https://pub.dev/packages/get_it)
|
||||
- Clean CLI for matrix runs and output formats (Markdown, CSV, JSON, pretty)
|
||||
- Reports metrics: timings, memory (RSS, peak), statistical spreads, and more
|
||||
- Extendable via your own DIAdapter or benchmark scenarios
|
||||
|
||||
---
|
||||
|
||||
## Benchmark Scenarios
|
||||
|
||||
- **registerSingleton**: Simple singleton registration/resolution
|
||||
- **chainSingleton**: Resolution of long singleton chains (A→B→C...)
|
||||
- **chainFactory**: Chain resolution via factories (new instances each time)
|
||||
- **asyncChain**: Async chain (with async providers)
|
||||
- **named**: Named/qualified resolution (e.g. from multiple implementations)
|
||||
- **override**: Resolution and override in subScopes/child adapters
|
||||
|
||||
---
|
||||
|
||||
## Supported DI
|
||||
|
||||
- **cherrypick** (default)
|
||||
- **get_it**
|
||||
- Easy to add your own DI by creating a DIAdapter
|
||||
|
||||
Switch DI with the CLI option: `--di`
|
||||
|
||||
---
|
||||
|
||||
## How to Run
|
||||
|
||||
1. **Install dependencies:**
|
||||
```shell
|
||||
dart pub get
|
||||
```
|
||||
|
||||
2. **Run all benchmarks (default: all scenarios, 2 warmup, 2 repeats):**
|
||||
```shell
|
||||
dart run bin/main.dart --benchmark=all --format=markdown
|
||||
```
|
||||
|
||||
3. **For get_it:**
|
||||
```shell
|
||||
dart run bin/main.dart --di=getit --benchmark=all --format=markdown
|
||||
```
|
||||
|
||||
4. **Show all CLI options:**
|
||||
```shell
|
||||
dart run bin/main.dart --help
|
||||
```
|
||||
|
||||
### CLI Parameters
|
||||
|
||||
- `--di` — DI implementation: `cherrypick` (default) or `getit`
|
||||
- `--benchmark, -b` — Scenario: `registerSingleton`, `chainSingleton`, `chainFactory`, `asyncChain`, `named`, `override`, `all`
|
||||
- `--chainCount, -c` — Number of parallel chains (e.g. `10,100`)
|
||||
- `--nestingDepth, -d` — Chain depth (e.g. `5,10`)
|
||||
- `--repeat, -r` — Measurement repeats (default: 2)
|
||||
- `--warmup, -w` — Warmup runs (default: 1)
|
||||
- `--format, -f` — Output: `pretty`, `csv`, `json`, `markdown`
|
||||
- `--help, -h` — Usage
|
||||
|
||||
### Run Examples
|
||||
|
||||
- **All benchmarks for cherrypick:**
|
||||
```shell
|
||||
dart run bin/main.dart --di=cherrypick --benchmark=all --format=markdown
|
||||
```
|
||||
|
||||
- **For get_it (all scenarios):**
|
||||
```shell
|
||||
dart run bin/main.dart --di=getit --benchmark=all --format=markdown
|
||||
```
|
||||
|
||||
- **Specify chains/depth matrix:**
|
||||
```shell
|
||||
dart run bin/main.dart --benchmark=chainSingleton --chainCount=10,100 --nestingDepth=5,10 --repeat=3 --format=csv
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Universal DI registration: Adapter-centric approach
|
||||
|
||||
Starting from vX.Y.Z, all DI registration scenarios and logic are encapsulated in the adapter itself via the `universalRegistration` method.
|
||||
|
||||
### How to use (in Dart code):
|
||||
|
||||
```dart
|
||||
final di = CherrypickDIAdapter(); // or GetItAdapter(), RiverpodAdapter(), etc
|
||||
|
||||
di.setupDependencies(
|
||||
di.universalRegistration(
|
||||
scenario: UniversalScenario.chain,
|
||||
chainCount: 10,
|
||||
nestingDepth: 5,
|
||||
bindingMode: UniversalBindingMode.singletonStrategy,
|
||||
),
|
||||
);
|
||||
```
|
||||
- There is **no more need to use any global function or switch**: each adapter provides its own type-safe implementation.
|
||||
|
||||
### How to add a new scenario or DI:
|
||||
- Implement `universalRegistration<S extends Enum>(...)` in your adapter
|
||||
- Use your own Enum if you want adapter-specific scenarios!
|
||||
- Benchmarks and CLI become automatically extensible for custom DI and scenarios.
|
||||
|
||||
### CLI usage (runs all universal scenarios for Cherrypick, GetIt, Riverpod):
|
||||
|
||||
```
|
||||
dart run bin/main.dart --di=cherrypick --benchmark=all
|
||||
dart run bin/main.dart --di=getit --benchmark=all
|
||||
dart run bin/main.dart --di=riverpod --benchmark=all
|
||||
```
|
||||
|
||||
See the `benchmark_di/lib/di_adapters/` folder for ready-to-use adapters.
|
||||
|
||||
---
|
||||
## Advantages
|
||||
|
||||
- **Type-safe:** Zero dynamic/object usage in DI flows.
|
||||
- **Extensible:** New scenarios are just new Enum values and a method extension.
|
||||
- **No global registration logic:** All DI-related logic is where it belongs: in the adapter.
|
||||
|
||||
=======
|
||||
## How to Add Your Own DI
|
||||
|
||||
1. Implement a class extending `DIAdapter` (`lib/di_adapters/your_adapter.dart`)
|
||||
2. Implement the `universalRegistration<S extends Enum>(...)` method directly in your adapter for type-safe and scenario-specific registration
|
||||
3. Register your adapter in CLI (see `cli/benchmark_cli.dart`)
|
||||
4. No global function needed — all logic is within the adapter!
|
||||
|
||||
---
|
||||
## Universal DI registration: Adapter-centric approach
|
||||
|
||||
Starting from vX.Y.Z, all DI registration scenarios and logic are encapsulated in the adapter itself via the `universalRegistration` method.
|
||||
|
||||
### How to use (in Dart code):
|
||||
|
||||
```dart
|
||||
final di = CherrypickDIAdapter(); // or GetItAdapter(), RiverpodAdapter(), etc
|
||||
|
||||
di.setupDependencies(
|
||||
di.universalRegistration(
|
||||
scenario: UniversalScenario.chain,
|
||||
chainCount: 10,
|
||||
nestingDepth: 5,
|
||||
bindingMode: UniversalBindingMode.singletonStrategy,
|
||||
),
|
||||
);
|
||||
```
|
||||
- There is **no more need to use any global function or switch**: each adapter provides its own type-safe implementation.
|
||||
|
||||
### How to add a new scenario or DI:
|
||||
- Implement `universalRegistration<S extends Enum>(...)` in your adapter
|
||||
- Use your own Enum if you want adapter-specific scenarios!
|
||||
- Benchmarks and CLI become automatically extensible for custom DI and scenarios.
|
||||
|
||||
### CLI usage (runs all universal scenarios for Cherrypick, GetIt, Riverpod):
|
||||
|
||||
```
|
||||
dart run bin/main.dart --di=cherrypick --benchmark=all
|
||||
dart run bin/main.dart --di=getit --benchmark=all
|
||||
dart run bin/main.dart --di=riverpod --benchmark=all
|
||||
```
|
||||
|
||||
See the `benchmark_di/lib/di_adapters/` folder for ready-to-use adapters.
|
||||
|
||||
## Advantages
|
||||
|
||||
- **Type-safe:** Zero dynamic/object usage in DI flows.
|
||||
- **Extensible:** New scenarios are just new Enum values and a method extension.
|
||||
- **No global registration logic:** All DI-related logic is where it belongs: in the adapter.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
classDiagram
|
||||
class BenchmarkCliRunner {
|
||||
+run(args)
|
||||
}
|
||||
class UniversalChainBenchmark~TContainer~ {
|
||||
+setup()
|
||||
+run()
|
||||
+teardown()
|
||||
}
|
||||
class UniversalChainAsyncBenchmark~TContainer~ {
|
||||
+setup()
|
||||
+run()
|
||||
+teardown()
|
||||
}
|
||||
class DIAdapter~TContainer~ {
|
||||
<<interface>>
|
||||
+setupDependencies(cb)
|
||||
+resolve~T~(named)
|
||||
+resolveAsync~T~(named)
|
||||
+teardown()
|
||||
+openSubScope(name)
|
||||
+waitForAsyncReady()
|
||||
+universalRegistration<S extends Enum>(...)
|
||||
}
|
||||
class CherrypickDIAdapter
|
||||
class GetItAdapter
|
||||
class RiverpodAdapter
|
||||
class UniversalChainModule {
|
||||
+builder(scope)
|
||||
+chainCount
|
||||
+nestingDepth
|
||||
+bindingMode
|
||||
+scenario
|
||||
}
|
||||
class UniversalService {
|
||||
<<interface>>
|
||||
+value
|
||||
+dependency
|
||||
}
|
||||
class UniversalServiceImpl {
|
||||
+UniversalServiceImpl(value, dependency)
|
||||
}
|
||||
class Scope
|
||||
class UniversalScenario
|
||||
class UniversalBindingMode
|
||||
|
||||
%% Relationships
|
||||
|
||||
BenchmarkCliRunner --> UniversalChainBenchmark
|
||||
BenchmarkCliRunner --> UniversalChainAsyncBenchmark
|
||||
|
||||
UniversalChainBenchmark *-- DIAdapter
|
||||
UniversalChainAsyncBenchmark *-- DIAdapter
|
||||
|
||||
DIAdapter <|.. CherrypickDIAdapter
|
||||
DIAdapter <|.. GetItAdapter
|
||||
DIAdapter <|.. RiverpodAdapter
|
||||
|
||||
CherrypickDIAdapter ..> Scope
|
||||
GetItAdapter ..> GetIt: "uses GetIt"
|
||||
RiverpodAdapter ..> Map~String, ProviderBase~: "uses Provider registry"
|
||||
|
||||
DIAdapter o--> UniversalChainModule : setupDependencies
|
||||
|
||||
UniversalChainModule ..> UniversalScenario
|
||||
UniversalChainModule ..> UniversalBindingMode
|
||||
|
||||
UniversalChainModule o-- UniversalServiceImpl : creates
|
||||
UniversalService <|.. UniversalServiceImpl
|
||||
UniversalServiceImpl --> UniversalService : dependency
|
||||
|
||||
%%
|
||||
%% Each concrete adapter implements universalRegistration<S extends Enum>
|
||||
%% You can add new scenario enums for custom adapters
|
||||
%% Extensibility is achieved via adapter logic, not global functions
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Metrics
|
||||
|
||||
Always collected:
|
||||
- **Timings** (microseconds): mean, median, stddev, min, max
|
||||
- **Memory**: RSS difference, peak RSS
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
@@ -1,226 +0,0 @@
|
||||
# benchmark_di
|
||||
|
||||
_Бенчмаркинговый набор для cherrypick, get_it и других DI-контейнеров._
|
||||
|
||||
## Общее описание
|
||||
|
||||
benchmark_di — это современный фреймворк для измерения производительности DI-контейнеров (как cherrypick, так и get_it) на синтетических, сложных и реальных сценариях: цепочки зависимостей, factory, async, именованные биндинги, override и пр.
|
||||
|
||||
**Возможности:**
|
||||
- Универсальный слой регистрации сценариев (работает с любым DI)
|
||||
- Готовая поддержка [cherrypick](https://github.com/) и [get_it](https://pub.dev/packages/get_it)
|
||||
- Удобный CLI для запусков по матрице значений параметров и различных форматов вывода (Markdown, CSV, JSON, pretty)
|
||||
- Сбор и вывод метрик: время, память (RSS, peak), статистика (среднее, медиана, stddev, min/max)
|
||||
- Легко расширять — создавайте свой DIAdapter и новые сценарии
|
||||
|
||||
---
|
||||
|
||||
## Сценарии бенчмарков
|
||||
|
||||
- **registerSingleton**: Регистрация и резолвинг singleton
|
||||
- **chainSingleton**: Разрешение длинных singleton-цепочек (A→B→C…)
|
||||
- **chainFactory**: То же, но с factory (каждый раз — новый объект)
|
||||
- **asyncChain**: Асинхронная цепочка (async factory/provider)
|
||||
- **named**: Разрешение по имени (например, из нескольких реализаций)
|
||||
- **override**: Переопределение зависимостей в subScope
|
||||
|
||||
---
|
||||
|
||||
## Поддерживаемые DI-контейнеры
|
||||
|
||||
- **cherrypick** (по умолчанию)
|
||||
- **get_it**
|
||||
- Легко добавить свой DI через DIAdapter
|
||||
|
||||
Меняется одной CLI-опцией: `--di`
|
||||
|
||||
---
|
||||
|
||||
## Как запустить
|
||||
|
||||
1. **Установить зависимости:**
|
||||
```shell
|
||||
dart pub get
|
||||
```
|
||||
|
||||
2. **Запустить все бенчмарки (по умолчанию: все сценарии, 2 прогрева, 2 замера):**
|
||||
```shell
|
||||
dart run bin/main.dart --benchmark=all --format=markdown
|
||||
```
|
||||
|
||||
3. **Для get_it:**
|
||||
```shell
|
||||
dart run bin/main.dart --di=getit --benchmark=all --format=markdown
|
||||
```
|
||||
|
||||
4. **Показать все опции CLI:**
|
||||
```shell
|
||||
dart run bin/main.dart --help
|
||||
```
|
||||
|
||||
### Параметры CLI
|
||||
|
||||
- `--di` — Какой DI использовать: `cherrypick` (по умолчанию) или `getit`
|
||||
- `--benchmark, -b` — Сценарий: `registerSingleton`, `chainSingleton`, `chainFactory`, `asyncChain`, `named`, `override`, `all`
|
||||
- `--chainCount, -c` — Сколько параллельных цепочек (например, `10,100`)
|
||||
- `--nestingDepth, -d` — Глубина цепочки (например, `5,10`)
|
||||
- `--repeat, -r` — Повторов замера (по умолчанию 2)
|
||||
- `--warmup, -w` — Прогревочных запусков (по умолчанию 1)
|
||||
- `--format, -f` — Формат отчёта: `pretty`, `csv`, `json`, `markdown`
|
||||
- `--help, -h` — Справка
|
||||
|
||||
### Примеры запуска
|
||||
|
||||
- **Все бенчмарки для cherrypick:**
|
||||
```shell
|
||||
dart run bin/main.dart --di=cherrypick --benchmark=all --format=markdown
|
||||
```
|
||||
|
||||
- **Для get_it (все сценарии):**
|
||||
```shell
|
||||
dart run bin/main.dart --di=getit --benchmark=all --format=markdown
|
||||
```
|
||||
|
||||
- **Запуск по матрице параметров:**
|
||||
```shell
|
||||
dart run bin/main.dart --benchmark=chainSingleton --chainCount=10,100 --nestingDepth=5,10 --repeat=3 --format=csv
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Универсальная регистрация зависимостей: теперь через adapter
|
||||
|
||||
В версии X.Y.Z вся логика сценариев регистрации DI-инфраструктуры локализована в adapter через метод `universalRegistration`.
|
||||
|
||||
### Использование в Dart:
|
||||
|
||||
```dart
|
||||
final di = CherrypickDIAdapter(); // или GetItAdapter(), RiverpodAdapter() и т.д.
|
||||
|
||||
di.setupDependencies(
|
||||
di.universalRegistration(
|
||||
scenario: UniversalScenario.chain,
|
||||
chainCount: 10,
|
||||
nestingDepth: 5,
|
||||
bindingMode: UniversalBindingMode.singletonStrategy,
|
||||
),
|
||||
);
|
||||
```
|
||||
- **Теперь нет необходимости вызывать глобальные функции или switch-case по типу DI!** Каждый adapter сам предоставляет типобезопасную функцию регистрации.
|
||||
|
||||
### Как добавить новый сценарий или DI:
|
||||
|
||||
- Реализуйте метод `universalRegistration<S extends Enum>(...)` в своём adapter.
|
||||
- Можно использовать как UniversalScenario, так и собственные enum-сценарии!
|
||||
- Бенчмарки CLI автоматически расширяются под ваш DI и ваши сценарии, если реализован метод-расширение.
|
||||
|
||||
### Запуск CLI (все сценарии DI Cherrypick, GetIt, Riverpod):
|
||||
|
||||
```
|
||||
dart run bin/main.dart --di=cherrypick --benchmark=all
|
||||
dart run bin/main.dart --di=getit --benchmark=all
|
||||
dart run bin/main.dart --di=riverpod --benchmark=all
|
||||
```
|
||||
|
||||
Смотрите примеры готовых adapters в `benchmark_di/lib/di_adapters/`.
|
||||
|
||||
## Преимущества
|
||||
|
||||
- **Type-safe:** Исключено использование dynamic/object в стороне DI.
|
||||
- **Масштабируемость:** Новый сценарий — просто enum + метод в adapter.
|
||||
- **Вся логика регистрации теперь только в adapter:** Добавление или изменение не затрагивает глобальные функции.
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Архитектура
|
||||
|
||||
```mermaid
|
||||
classDiagram
|
||||
class BenchmarkCliRunner {
|
||||
+run(args)
|
||||
}
|
||||
class UniversalChainBenchmark~TContainer~ {
|
||||
+setup()
|
||||
+run()
|
||||
+teardown()
|
||||
}
|
||||
class UniversalChainAsyncBenchmark~TContainer~ {
|
||||
+setup()
|
||||
+run()
|
||||
+teardown()
|
||||
}
|
||||
class DIAdapter~TContainer~ {
|
||||
<<interface>>
|
||||
+setupDependencies(cb)
|
||||
+resolve~T~(named)
|
||||
+resolveAsync~T~(named)
|
||||
+teardown()
|
||||
+openSubScope(name)
|
||||
+waitForAsyncReady()
|
||||
+universalRegistration<S extends Enum>(...)
|
||||
}
|
||||
class CherrypickDIAdapter
|
||||
class GetItAdapter
|
||||
class RiverpodAdapter
|
||||
class UniversalChainModule {
|
||||
+builder(scope)
|
||||
+chainCount
|
||||
+nestingDepth
|
||||
+bindingMode
|
||||
+scenario
|
||||
}
|
||||
class UniversalService {
|
||||
<<interface>>
|
||||
+value
|
||||
+dependency
|
||||
}
|
||||
class UniversalServiceImpl {
|
||||
+UniversalServiceImpl(value, dependency)
|
||||
}
|
||||
class Scope
|
||||
class UniversalScenario
|
||||
class UniversalBindingMode
|
||||
|
||||
%% Relationships
|
||||
|
||||
BenchmarkCliRunner --> UniversalChainBenchmark
|
||||
BenchmarkCliRunner --> UniversalChainAsyncBenchmark
|
||||
|
||||
UniversalChainBenchmark *-- DIAdapter
|
||||
UniversalChainAsyncBenchmark *-- DIAdapter
|
||||
|
||||
DIAdapter <|.. CherrypickDIAdapter
|
||||
DIAdapter <|.. GetItAdapter
|
||||
DIAdapter <|.. RiverpodAdapter
|
||||
|
||||
CherrypickDIAdapter ..> Scope
|
||||
GetItAdapter ..> GetIt: "uses GetIt"
|
||||
RiverpodAdapter ..> Map~String, ProviderBase~: "uses Provider registry"
|
||||
|
||||
DIAdapter o--> UniversalChainModule : setupDependencies
|
||||
|
||||
UniversalChainModule ..> UniversalScenario
|
||||
UniversalChainModule ..> UniversalBindingMode
|
||||
|
||||
UniversalChainModule o-- UniversalServiceImpl : creates
|
||||
UniversalService <|.. UniversalServiceImpl
|
||||
UniversalServiceImpl --> UniversalService : dependency
|
||||
|
||||
%%
|
||||
%% Each concrete adapter implements universalRegistration<S extends Enum>
|
||||
%% You can add new scenario enums for custom adapters
|
||||
%% Extensibility is achieved via adapter logic, not global functions
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Метрики
|
||||
|
||||
Всегда собираются:
|
||||
- **Время** (мкс): среднее, медиана, stddev, min, max
|
||||
- **Память**: прирост RSS, пиковое значение RSS
|
||||
|
||||
## Лицензия
|
||||
|
||||
MIT
|
||||
@@ -1,51 +0,0 @@
|
||||
# Comparative DI Benchmark Report: cherrypick vs get_it vs riverpod
|
||||
|
||||
## Benchmark Scenarios
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## Comparative Table: chainCount=10, nestingDepth=10 (Mean, PeakRSS)
|
||||
|
||||
| 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 |
|
||||
|
||||
## Maximum Load: chainCount=100, nestingDepth=100 (Mean, PeakRSS)
|
||||
|
||||
| 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 |
|
||||
|
||||
---
|
||||
|
||||
## Analysis
|
||||
|
||||
- **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.
|
||||
|
||||
### 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.
|
||||
|
||||
---
|
||||
|
||||
_Last updated: August 8, 2025._
|
||||
@@ -1,51 +0,0 @@
|
||||
# Сравнительный отчет DI-бенчмарка: cherrypick vs get_it vs riverpod
|
||||
|
||||
## Описание сценариев
|
||||
|
||||
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)
|
||||
|
||||
| Сценарий | 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 |
|
||||
|
||||
## Максимальная нагрузка: chainCount=100, nestingDepth=100 (Mean, PeakRSS)
|
||||
|
||||
| Сценарий | 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 |
|
||||
|
||||
---
|
||||
|
||||
## Краткий анализ и рекомендации
|
||||
|
||||
- **get_it** всегда лидер, особенно на глубине/асинхронных графах.
|
||||
- **cherrypick** заметно быстрее riverpod на сложных сценариях, опережая его в разы.
|
||||
- **riverpod** подходит только для простых/небольших графов — при росте глубины или async/override резко проигрывает по скорости.
|
||||
|
||||
### Рекомендации
|
||||
- Используйте **get_it** для критичных к скорости приложений/сложных графов зависимостей.
|
||||
- Выбирайте **cherrypick** для масштабируемых, тестируемых архитектур, если микросекундная разница не критична.
|
||||
- **riverpod** уместен только для реактивного UI или простых графов DI.
|
||||
|
||||
---
|
||||
|
||||
_Обновлено: 8 августа 2025_
|
||||
@@ -1,34 +0,0 @@
|
||||
# This file configures the static analysis results for your project (errors,
|
||||
# warnings, and lints).
|
||||
#
|
||||
# This enables the 'recommended' set of lints from `package:lints`.
|
||||
# This set helps identify many issues that may lead to problems when running
|
||||
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
|
||||
# style and format.
|
||||
#
|
||||
# If you want a smaller set of lints you can change this to specify
|
||||
# 'package:lints/core.yaml'. These are just the most critical lints
|
||||
# (the recommended set includes the core lints).
|
||||
# The core lints are also what is used by pub.dev for scoring packages.
|
||||
|
||||
include: package:lints/recommended.yaml
|
||||
analyzer:
|
||||
errors:
|
||||
deprecated_member_use: ignore
|
||||
depend_on_referenced_packages: ignore
|
||||
|
||||
# Uncomment the following section to specify additional rules.
|
||||
|
||||
# linter:
|
||||
# rules:
|
||||
# - camel_case_types
|
||||
|
||||
# analyzer:
|
||||
# exclude:
|
||||
# - path/to/excluded/files/**
|
||||
|
||||
# For more information about the core and recommended set of lints, see
|
||||
# https://dart.dev/go/core-lints
|
||||
|
||||
# For additional information about configuring this file, see
|
||||
# https://dart.dev/guides/language/analysis-options
|
||||
@@ -1,5 +0,0 @@
|
||||
import 'package:benchmark_di/cli/benchmark_cli.dart';
|
||||
|
||||
Future<void> main(List<String> args) async {
|
||||
await BenchmarkCliRunner().run(args);
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import 'package:benchmark_di/scenarios/universal_binding_mode.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_scenario.dart';
|
||||
import 'package:benchmark_harness/benchmark_harness.dart';
|
||||
import 'package:benchmark_di/di_adapters/di_adapter.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_service.dart';
|
||||
|
||||
class UniversalChainAsyncBenchmark<TContainer> extends AsyncBenchmarkBase {
|
||||
final DIAdapter<TContainer> di;
|
||||
final int chainCount;
|
||||
final int nestingDepth;
|
||||
final UniversalBindingMode mode;
|
||||
|
||||
UniversalChainAsyncBenchmark(
|
||||
this.di, {
|
||||
this.chainCount = 1,
|
||||
this.nestingDepth = 3,
|
||||
this.mode = UniversalBindingMode.asyncStrategy,
|
||||
}) : super('UniversalAsync: asyncChain/$mode CD=$chainCount/$nestingDepth');
|
||||
|
||||
@override
|
||||
Future<void> setup() async {
|
||||
di.setupDependencies(di.universalRegistration(
|
||||
chainCount: chainCount,
|
||||
nestingDepth: nestingDepth,
|
||||
bindingMode: mode,
|
||||
scenario: UniversalScenario.asyncChain,
|
||||
));
|
||||
await di.waitForAsyncReady();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> teardown() async {
|
||||
di.teardown();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> run() async {
|
||||
final serviceName = '${chainCount}_$nestingDepth';
|
||||
await di.resolveAsync<UniversalService>(named: serviceName);
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
import 'package:benchmark_di/scenarios/universal_binding_mode.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_scenario.dart';
|
||||
import 'package:benchmark_harness/benchmark_harness.dart';
|
||||
import 'package:benchmark_di/di_adapters/di_adapter.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_service.dart';
|
||||
|
||||
class UniversalChainBenchmark<TContainer> extends BenchmarkBase {
|
||||
final DIAdapter<TContainer> _di;
|
||||
final int chainCount;
|
||||
final int nestingDepth;
|
||||
final UniversalBindingMode mode;
|
||||
final UniversalScenario scenario;
|
||||
DIAdapter<TContainer>? _childDi;
|
||||
|
||||
UniversalChainBenchmark(
|
||||
this._di, {
|
||||
this.chainCount = 1,
|
||||
this.nestingDepth = 3,
|
||||
this.mode = UniversalBindingMode.singletonStrategy,
|
||||
this.scenario = UniversalScenario.chain,
|
||||
}) : super('Universal: $scenario/$mode CD=$chainCount/$nestingDepth');
|
||||
|
||||
@override
|
||||
void setup() {
|
||||
switch (scenario) {
|
||||
case UniversalScenario.override:
|
||||
_di.setupDependencies(_di.universalRegistration(
|
||||
chainCount: chainCount,
|
||||
nestingDepth: nestingDepth,
|
||||
bindingMode: UniversalBindingMode.singletonStrategy,
|
||||
scenario: UniversalScenario.chain,
|
||||
));
|
||||
_childDi = _di.openSubScope('child');
|
||||
_childDi!.setupDependencies(_childDi!.universalRegistration(
|
||||
chainCount: chainCount,
|
||||
nestingDepth: nestingDepth,
|
||||
bindingMode: UniversalBindingMode.singletonStrategy,
|
||||
scenario: UniversalScenario.chain,
|
||||
));
|
||||
break;
|
||||
default:
|
||||
_di.setupDependencies(_di.universalRegistration(
|
||||
chainCount: chainCount,
|
||||
nestingDepth: nestingDepth,
|
||||
bindingMode: mode,
|
||||
scenario: scenario,
|
||||
));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void teardown() => _di.teardown();
|
||||
|
||||
@override
|
||||
void run() {
|
||||
switch (scenario) {
|
||||
case UniversalScenario.register:
|
||||
_di.resolve<UniversalService>();
|
||||
break;
|
||||
case UniversalScenario.named:
|
||||
if (_di.runtimeType.toString().contains('GetItAdapter')) {
|
||||
_di.resolve<UniversalService>(named: 'impl2');
|
||||
} else {
|
||||
_di.resolve<UniversalService>(named: 'impl2');
|
||||
}
|
||||
break;
|
||||
case UniversalScenario.chain:
|
||||
final serviceName = '${chainCount}_$nestingDepth';
|
||||
_di.resolve<UniversalService>(named: serviceName);
|
||||
break;
|
||||
case UniversalScenario.override:
|
||||
_childDi!.resolve<UniversalService>();
|
||||
break;
|
||||
case UniversalScenario.asyncChain:
|
||||
throw UnsupportedError('asyncChain supported only in UniversalChainAsyncBenchmark');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:benchmark_di/cli/report/markdown_report.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_scenario.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:riverpod/riverpod.dart' as rp;
|
||||
|
||||
import 'report/pretty_report.dart';
|
||||
import 'report/csv_report.dart';
|
||||
import 'report/json_report.dart';
|
||||
import 'parser.dart';
|
||||
import 'runner.dart';
|
||||
import 'package:benchmark_di/benchmarks/universal_chain_benchmark.dart';
|
||||
import 'package:benchmark_di/benchmarks/universal_chain_async_benchmark.dart';
|
||||
import 'package:benchmark_di/di_adapters/cherrypick_adapter.dart';
|
||||
import 'package:benchmark_di/di_adapters/get_it_adapter.dart';
|
||||
import 'package:benchmark_di/di_adapters/riverpod_adapter.dart';
|
||||
|
||||
/// Command-line interface (CLI) runner for benchmarks.
|
||||
///
|
||||
/// Parses CLI arguments, orchestrates benchmarks for different
|
||||
/// scenarios and configurations, collects results, and generates reports
|
||||
/// in the desired output format.
|
||||
class BenchmarkCliRunner {
|
||||
/// Runs benchmarks based on CLI [args], configuring different test scenarios.
|
||||
Future<void> run(List<String> args) async {
|
||||
final config = parseBenchmarkCli(args);
|
||||
final results = <Map<String, dynamic>>[];
|
||||
for (final bench in config.benchesToRun) {
|
||||
final scenario = toScenario(bench);
|
||||
final mode = toMode(bench);
|
||||
for (final c in config.chainCounts) {
|
||||
for (final d in config.nestDepths) {
|
||||
BenchmarkResult benchResult;
|
||||
if (config.di == 'getit') {
|
||||
final di = GetItAdapter();
|
||||
if (scenario == UniversalScenario.asyncChain) {
|
||||
final benchAsync = UniversalChainAsyncBenchmark<GetIt>(di,
|
||||
chainCount: c, nestingDepth: d, mode: mode,
|
||||
);
|
||||
benchResult = await BenchmarkRunner.runAsync(
|
||||
benchmark: benchAsync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
);
|
||||
} else {
|
||||
final benchSync = UniversalChainBenchmark<GetIt>(di,
|
||||
chainCount: c, nestingDepth: d, mode: mode, scenario: scenario,
|
||||
);
|
||||
benchResult = await BenchmarkRunner.runSync(
|
||||
benchmark: benchSync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
);
|
||||
}
|
||||
} else if (config.di == 'riverpod') {
|
||||
final di = RiverpodAdapter();
|
||||
if (scenario == UniversalScenario.asyncChain) {
|
||||
final benchAsync = UniversalChainAsyncBenchmark<Map<String, rp.ProviderBase<Object?>>>(di,
|
||||
chainCount: c, nestingDepth: d, mode: mode,
|
||||
);
|
||||
benchResult = await BenchmarkRunner.runAsync(
|
||||
benchmark: benchAsync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
);
|
||||
} else {
|
||||
final benchSync = UniversalChainBenchmark<Map<String, rp.ProviderBase<Object?>>>(di,
|
||||
chainCount: c, nestingDepth: d, mode: mode, scenario: scenario,
|
||||
);
|
||||
benchResult = await BenchmarkRunner.runSync(
|
||||
benchmark: benchSync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
final di = CherrypickDIAdapter();
|
||||
if (scenario == UniversalScenario.asyncChain) {
|
||||
final benchAsync = UniversalChainAsyncBenchmark<Scope>(di,
|
||||
chainCount: c, nestingDepth: d, mode: mode,
|
||||
);
|
||||
benchResult = await BenchmarkRunner.runAsync(
|
||||
benchmark: benchAsync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
);
|
||||
} else {
|
||||
final benchSync = UniversalChainBenchmark<Scope>(di,
|
||||
chainCount: c, nestingDepth: d, mode: mode, scenario: scenario,
|
||||
);
|
||||
benchResult = await BenchmarkRunner.runSync(
|
||||
benchmark: benchSync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
);
|
||||
}
|
||||
}
|
||||
final timings = benchResult.timings;
|
||||
timings.sort();
|
||||
var mean = timings.reduce((a, b) => a + b) / timings.length;
|
||||
var median = timings[timings.length ~/ 2];
|
||||
var minVal = timings.first;
|
||||
var maxVal = timings.last;
|
||||
var stddev = timings.isEmpty ? 0 : sqrt(timings.map((x) => pow(x - mean, 2)).reduce((a, b) => a + b) / timings.length);
|
||||
results.add({
|
||||
'benchmark': 'Universal_$bench',
|
||||
'chainCount': c,
|
||||
'nestingDepth': d,
|
||||
'mean_us': mean.toStringAsFixed(2),
|
||||
'median_us': median.toStringAsFixed(2),
|
||||
'stddev_us': stddev.toStringAsFixed(2),
|
||||
'min_us': minVal.toStringAsFixed(2),
|
||||
'max_us': maxVal.toStringAsFixed(2),
|
||||
'trials': timings.length,
|
||||
'timings_us': timings.map((t) => t.toStringAsFixed(2)).toList(),
|
||||
'memory_diff_kb': benchResult.memoryDiffKb,
|
||||
'delta_peak_kb': benchResult.deltaPeakKb,
|
||||
'peak_rss_kb': benchResult.peakRssKb,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
final reportGenerators = {
|
||||
'pretty': PrettyReport(),
|
||||
'csv': CsvReport(),
|
||||
'json': JsonReport(),
|
||||
'markdown': MarkdownReport(),
|
||||
};
|
||||
print(reportGenerators[config.format]?.render(results) ?? PrettyReport().render(results));
|
||||
}
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:args/args.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_binding_mode.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_scenario.dart';
|
||||
|
||||
/// Enum describing all supported Universal DI benchmark types.
|
||||
enum UniversalBenchmark {
|
||||
/// Simple singleton registration benchmark
|
||||
registerSingleton,
|
||||
/// Chain of singleton dependencies
|
||||
chainSingleton,
|
||||
/// Chain using factories
|
||||
chainFactory,
|
||||
/// Async chain resolution
|
||||
chainAsync,
|
||||
/// Named registration benchmark
|
||||
named,
|
||||
/// Override/child-scope benchmark
|
||||
override,
|
||||
}
|
||||
|
||||
/// Maps [UniversalBenchmark] to the scenario enum for DI chains.
|
||||
UniversalScenario toScenario(UniversalBenchmark b) {
|
||||
switch (b) {
|
||||
case UniversalBenchmark.registerSingleton:
|
||||
return UniversalScenario.register;
|
||||
case UniversalBenchmark.chainSingleton:
|
||||
return UniversalScenario.chain;
|
||||
case UniversalBenchmark.chainFactory:
|
||||
return UniversalScenario.chain;
|
||||
case UniversalBenchmark.chainAsync:
|
||||
return UniversalScenario.asyncChain;
|
||||
case UniversalBenchmark.named:
|
||||
return UniversalScenario.named;
|
||||
case UniversalBenchmark.override:
|
||||
return UniversalScenario.override;
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps benchmark to registration mode (singleton/factory/async).
|
||||
UniversalBindingMode toMode(UniversalBenchmark b) {
|
||||
switch (b) {
|
||||
case UniversalBenchmark.registerSingleton:
|
||||
return UniversalBindingMode.singletonStrategy;
|
||||
case UniversalBenchmark.chainSingleton:
|
||||
return UniversalBindingMode.singletonStrategy;
|
||||
case UniversalBenchmark.chainFactory:
|
||||
return UniversalBindingMode.factoryStrategy;
|
||||
case UniversalBenchmark.chainAsync:
|
||||
return UniversalBindingMode.asyncStrategy;
|
||||
case UniversalBenchmark.named:
|
||||
return UniversalBindingMode.singletonStrategy;
|
||||
case UniversalBenchmark.override:
|
||||
return UniversalBindingMode.singletonStrategy;
|
||||
}
|
||||
}
|
||||
|
||||
/// Utility to parse a string into its corresponding enum value [T].
|
||||
T parseEnum<T>(String value, List<T> values, T defaultValue) {
|
||||
return values.firstWhere(
|
||||
(v) => v.toString().split('.').last.toLowerCase() == value.toLowerCase(),
|
||||
orElse: () => defaultValue,
|
||||
);
|
||||
}
|
||||
|
||||
/// Parses comma-separated integer list from [s].
|
||||
List<int> parseIntList(String s) =>
|
||||
s.split(',').map((e) => int.tryParse(e.trim()) ?? 0).where((x) => x > 0).toList();
|
||||
|
||||
/// CLI config describing what and how to benchmark.
|
||||
class BenchmarkCliConfig {
|
||||
/// Benchmarks enabled to run (scenarios).
|
||||
final List<UniversalBenchmark> benchesToRun;
|
||||
/// List of chain counts (parallel, per test).
|
||||
final List<int> chainCounts;
|
||||
/// List of nesting depths (max chain length, per test).
|
||||
final List<int> nestDepths;
|
||||
/// How many times to repeat each trial.
|
||||
final int repeats;
|
||||
/// How many times to warm-up before measuring.
|
||||
final int warmups;
|
||||
/// Output report format.
|
||||
final String format;
|
||||
/// Name of DI implementation ("cherrypick" or "getit")
|
||||
final String di;
|
||||
BenchmarkCliConfig({
|
||||
required this.benchesToRun,
|
||||
required this.chainCounts,
|
||||
required this.nestDepths,
|
||||
required this.repeats,
|
||||
required this.warmups,
|
||||
required this.format,
|
||||
required this.di,
|
||||
});
|
||||
}
|
||||
|
||||
/// Parses CLI arguments [args] into a [BenchmarkCliConfig].
|
||||
/// Supports --benchmark, --chainCount, --nestingDepth, etc.
|
||||
BenchmarkCliConfig parseBenchmarkCli(List<String> args) {
|
||||
final parser = ArgParser()
|
||||
..addOption('benchmark', abbr: 'b', defaultsTo: 'chainSingleton')
|
||||
..addOption('chainCount', abbr: 'c', defaultsTo: '10')
|
||||
..addOption('nestingDepth', abbr: 'd', defaultsTo: '5')
|
||||
..addOption('repeat', abbr: 'r', defaultsTo: '2')
|
||||
..addOption('warmup', abbr: 'w', defaultsTo: '1')
|
||||
..addOption('format', abbr: 'f', defaultsTo: 'pretty')
|
||||
..addOption('di', defaultsTo: 'cherrypick', help: 'DI implementation: cherrypick, getit or riverpod')
|
||||
..addFlag('help', abbr: 'h', negatable: false, help: 'Show help');
|
||||
final result = parser.parse(args);
|
||||
if (result['help'] == true) {
|
||||
print(parser.usage);
|
||||
exit(0);
|
||||
}
|
||||
final benchName = result['benchmark'] as String;
|
||||
final isAll = benchName == 'all';
|
||||
final allBenches = UniversalBenchmark.values;
|
||||
final benchesToRun = isAll
|
||||
? allBenches
|
||||
: [parseEnum(benchName, allBenches, UniversalBenchmark.chainSingleton)];
|
||||
return BenchmarkCliConfig(
|
||||
benchesToRun: benchesToRun,
|
||||
chainCounts: parseIntList(result['chainCount'] as String),
|
||||
nestDepths: parseIntList(result['nestingDepth'] as String),
|
||||
repeats: int.tryParse(result['repeat'] as String? ?? "") ?? 2,
|
||||
warmups: int.tryParse(result['warmup'] as String? ?? "") ?? 1,
|
||||
format: result['format'] as String,
|
||||
di: result['di'] as String? ?? 'cherrypick',
|
||||
);
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import 'report_generator.dart';
|
||||
|
||||
/// Generates a CSV-formatted report for benchmark results.
|
||||
class CsvReport extends ReportGenerator {
|
||||
/// List of all keys/columns to include in the CSV output.
|
||||
@override
|
||||
final List<String> keys = [
|
||||
'benchmark','chainCount','nestingDepth','mean_us','median_us','stddev_us',
|
||||
'min_us','max_us','trials','timings_us','memory_diff_kb','delta_peak_kb','peak_rss_kb'
|
||||
];
|
||||
/// Renders rows as a CSV table string.
|
||||
@override
|
||||
String render(List<Map<String, dynamic>> rows) {
|
||||
final header = keys.join(',');
|
||||
final lines = rows.map((r) =>
|
||||
keys.map((k) {
|
||||
final v = r[k];
|
||||
if (v is List) return '"${v.join(';')}"';
|
||||
return (v ?? '').toString();
|
||||
}).join(',')
|
||||
).toList();
|
||||
return ([header] + lines).join('\n');
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import 'report_generator.dart';
|
||||
|
||||
/// Generates a JSON-formatted report for benchmark results.
|
||||
class JsonReport extends ReportGenerator {
|
||||
/// No specific keys; outputs all fields in raw map.
|
||||
@override
|
||||
List<String> get keys => [];
|
||||
/// Renders all result rows as a pretty-printed JSON array.
|
||||
@override
|
||||
String render(List<Map<String, dynamic>> rows) {
|
||||
return '[\n${rows.map((r) => ' $r').join(',\n')}\n]';
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
import 'report_generator.dart';
|
||||
|
||||
/// Generates a Markdown-formatted report for benchmark results.
|
||||
///
|
||||
/// Displays result rows as a visually clear Markdown table including a legend for all metrics.
|
||||
class MarkdownReport extends ReportGenerator {
|
||||
/// List of columns (keys) to show in the Markdown table.
|
||||
@override
|
||||
final List<String> keys = [
|
||||
'benchmark','chainCount','nestingDepth','mean_us','median_us','stddev_us',
|
||||
'min_us','max_us','trials','memory_diff_kb','delta_peak_kb','peak_rss_kb'
|
||||
];
|
||||
|
||||
/// Friendly display names for each benchmark type.
|
||||
static const nameMap = {
|
||||
'Universal_UniversalBenchmark.registerSingleton':'RegisterSingleton',
|
||||
'Universal_UniversalBenchmark.chainSingleton':'ChainSingleton',
|
||||
'Universal_UniversalBenchmark.chainFactory':'ChainFactory',
|
||||
'Universal_UniversalBenchmark.chainAsync':'AsyncChain',
|
||||
'Universal_UniversalBenchmark.named':'Named',
|
||||
'Universal_UniversalBenchmark.override':'Override',
|
||||
};
|
||||
|
||||
/// Renders all results as a formatted Markdown table with aligned columns and a legend.
|
||||
@override
|
||||
String render(List<Map<String, dynamic>> rows) {
|
||||
final headers = [
|
||||
'Benchmark', 'Chain Count', 'Depth', 'Mean (us)', 'Median', 'Stddev', 'Min', 'Max', 'N', 'ΔRSS(KB)', 'ΔPeak(KB)', 'PeakRSS(KB)'
|
||||
];
|
||||
final dataRows = rows.map((r) {
|
||||
final readableName = nameMap[r['benchmark']] ?? r['benchmark'];
|
||||
return [
|
||||
readableName,
|
||||
r['chainCount'],
|
||||
r['nestingDepth'],
|
||||
r['mean_us'],
|
||||
r['median_us'],
|
||||
r['stddev_us'],
|
||||
r['min_us'],
|
||||
r['max_us'],
|
||||
r['trials'],
|
||||
r['memory_diff_kb'],
|
||||
r['delta_peak_kb'],
|
||||
r['peak_rss_kb'],
|
||||
].map((cell) => cell.toString()).toList();
|
||||
}).toList();
|
||||
|
||||
// Calculate column width for pretty alignment
|
||||
final all = [headers] + dataRows;
|
||||
final widths = List.generate(headers.length, (i) {
|
||||
return all.map((row) => row[i].length).reduce((a, b) => a > b ? a : b);
|
||||
});
|
||||
|
||||
String rowToLine(List<String> row, {String sep = ' | '}) =>
|
||||
'| ${List.generate(row.length, (i) => row[i].padRight(widths[i])).join(sep)} |';
|
||||
|
||||
final headerLine = rowToLine(headers);
|
||||
final divider = '| ${widths.map((w) => '-' * w).join(' | ')} |';
|
||||
final lines = dataRows.map(rowToLine).toList();
|
||||
|
||||
final legend = '''
|
||||
> **Legend:**
|
||||
> `Benchmark` – Test name
|
||||
> `Chain Count` – Number of independent chains
|
||||
> `Depth` – Depth of each chain
|
||||
> `Mean (us)` – Average time per run (microseconds)
|
||||
> `Median` – Median time per run
|
||||
> `Stddev` – Standard deviation
|
||||
> `Min`, `Max` – Min/max run time
|
||||
> `N` – Number of measurements
|
||||
> `ΔRSS(KB)` – Change in process memory (KB)
|
||||
> `ΔPeak(KB)` – Change in peak RSS (KB)
|
||||
> `PeakRSS(KB)` – Max observed RSS memory (KB)
|
||||
''';
|
||||
|
||||
return '$legend\n\n${([headerLine, divider] + lines).join('\n')}' ;
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
import 'report_generator.dart';
|
||||
|
||||
/// Generates a human-readable, tab-delimited report for benchmark results.
|
||||
///
|
||||
/// Used for terminal and log output; shows each result as a single line with labeled headers.
|
||||
class PrettyReport extends ReportGenerator {
|
||||
/// List of columns to output in the pretty report.
|
||||
@override
|
||||
final List<String> keys = [
|
||||
'benchmark','chainCount','nestingDepth','mean_us','median_us','stddev_us',
|
||||
'min_us','max_us','trials','memory_diff_kb','delta_peak_kb','peak_rss_kb'
|
||||
];
|
||||
|
||||
/// Mappings from internal benchmark IDs to display names.
|
||||
static const nameMap = {
|
||||
'Universal_UniversalBenchmark.registerSingleton': 'RegisterSingleton',
|
||||
'Universal_UniversalBenchmark.chainSingleton': 'ChainSingleton',
|
||||
'Universal_UniversalBenchmark.chainFactory': 'ChainFactory',
|
||||
'Universal_UniversalBenchmark.chainAsync': 'AsyncChain',
|
||||
'Universal_UniversalBenchmark.named': 'Named',
|
||||
'Universal_UniversalBenchmark.override': 'Override',
|
||||
};
|
||||
|
||||
/// Renders the results as a header + tab-separated value table.
|
||||
@override
|
||||
String render(List<Map<String, dynamic>> rows) {
|
||||
final headers = [
|
||||
'Benchmark', 'Chain Count', 'Depth', 'Mean (us)', 'Median', 'Stddev', 'Min', 'Max', 'N', 'ΔRSS(KB)', 'ΔPeak(KB)', 'PeakRSS(KB)'
|
||||
];
|
||||
final header = headers.join('\t');
|
||||
final lines = rows.map((r) {
|
||||
final readableName = nameMap[r['benchmark']] ?? r['benchmark'];
|
||||
return [
|
||||
readableName,
|
||||
r['chainCount'],
|
||||
r['nestingDepth'],
|
||||
r['mean_us'],
|
||||
r['median_us'],
|
||||
r['stddev_us'],
|
||||
r['min_us'],
|
||||
r['max_us'],
|
||||
r['trials'],
|
||||
r['memory_diff_kb'],
|
||||
r['delta_peak_kb'],
|
||||
r['peak_rss_kb'],
|
||||
].join('\t');
|
||||
}).toList();
|
||||
return ([header] + lines).join('\n');
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
/// Abstract base for generating benchmark result reports in different formats.
|
||||
///
|
||||
/// Subclasses implement [render] to output results, and [keys] to define columns (if any).
|
||||
abstract class ReportGenerator {
|
||||
/// Renders the given [results] as a formatted string (table, markdown, csv, etc).
|
||||
String render(List<Map<String, dynamic>> results);
|
||||
/// List of output columns/keys included in the export (or [] for auto/all).
|
||||
List<String> get keys;
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
import 'package:benchmark_di/benchmarks/universal_chain_benchmark.dart';
|
||||
import 'package:benchmark_di/benchmarks/universal_chain_async_benchmark.dart';
|
||||
|
||||
/// Holds the results for a single benchmark execution.
|
||||
class BenchmarkResult {
|
||||
/// List of timings for each run (in microseconds).
|
||||
final List<num> timings;
|
||||
/// Difference in memory (RSS, in KB) after running.
|
||||
final int memoryDiffKb;
|
||||
/// Difference between peak RSS and initial RSS (in KB).
|
||||
final int deltaPeakKb;
|
||||
/// Peak RSS memory observed (in KB).
|
||||
final int peakRssKb;
|
||||
BenchmarkResult({
|
||||
required this.timings,
|
||||
required this.memoryDiffKb,
|
||||
required this.deltaPeakKb,
|
||||
required this.peakRssKb,
|
||||
});
|
||||
/// Computes a BenchmarkResult instance from run timings and memory data.
|
||||
factory BenchmarkResult.collect({
|
||||
required List<num> timings,
|
||||
required List<int> rssValues,
|
||||
required int memBefore,
|
||||
}) {
|
||||
final memAfter = ProcessInfo.currentRss;
|
||||
final memDiffKB = ((memAfter - memBefore) / 1024).round();
|
||||
final peakRss = [...rssValues, memBefore].reduce(max);
|
||||
final deltaPeakKb = ((peakRss - memBefore) / 1024).round();
|
||||
return BenchmarkResult(
|
||||
timings: timings,
|
||||
memoryDiffKb: memDiffKB,
|
||||
deltaPeakKb: deltaPeakKb,
|
||||
peakRssKb: (peakRss / 1024).round(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Static methods to execute and time benchmarks for DI containers.
|
||||
class BenchmarkRunner {
|
||||
/// Runs a synchronous benchmark ([UniversalChainBenchmark]) for a given number of [warmups] and [repeats].
|
||||
/// Collects execution time and observed memory.
|
||||
static Future<BenchmarkResult> runSync({
|
||||
required UniversalChainBenchmark benchmark,
|
||||
required int warmups,
|
||||
required int repeats,
|
||||
}) async {
|
||||
final timings = <num>[];
|
||||
final rssValues = <int>[];
|
||||
for (int i = 0; i < warmups; i++) {
|
||||
benchmark.setup();
|
||||
benchmark.run();
|
||||
benchmark.teardown();
|
||||
}
|
||||
final memBefore = ProcessInfo.currentRss;
|
||||
for (int i = 0; i < repeats; i++) {
|
||||
benchmark.setup();
|
||||
final sw = Stopwatch()..start();
|
||||
benchmark.run();
|
||||
sw.stop();
|
||||
timings.add(sw.elapsedMicroseconds);
|
||||
rssValues.add(ProcessInfo.currentRss);
|
||||
benchmark.teardown();
|
||||
}
|
||||
return BenchmarkResult.collect(timings: timings, rssValues: rssValues, memBefore: memBefore);
|
||||
}
|
||||
|
||||
/// Runs an asynchronous benchmark ([UniversalChainAsyncBenchmark]) for a given number of [warmups] and [repeats].
|
||||
/// Collects execution time and observed memory.
|
||||
static Future<BenchmarkResult> runAsync({
|
||||
required UniversalChainAsyncBenchmark benchmark,
|
||||
required int warmups,
|
||||
required int repeats,
|
||||
}) async {
|
||||
final timings = <num>[];
|
||||
final rssValues = <int>[];
|
||||
for (int i = 0; i < warmups; i++) {
|
||||
await benchmark.setup();
|
||||
await benchmark.run();
|
||||
await benchmark.teardown();
|
||||
}
|
||||
final memBefore = ProcessInfo.currentRss;
|
||||
for (int i = 0; i < repeats; i++) {
|
||||
await benchmark.setup();
|
||||
final sw = Stopwatch()..start();
|
||||
await benchmark.run();
|
||||
sw.stop();
|
||||
timings.add(sw.elapsedMicroseconds);
|
||||
rssValues.add(ProcessInfo.currentRss);
|
||||
await benchmark.teardown();
|
||||
}
|
||||
return BenchmarkResult.collect(timings: timings, rssValues: rssValues, memBefore: memBefore);
|
||||
}
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
import 'package:benchmark_di/scenarios/universal_binding_mode.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_scenario.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_service.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'di_adapter.dart';
|
||||
|
||||
|
||||
/// Test module that generates a chain of service bindings for benchmarking.
|
||||
///
|
||||
/// Configurable by chain count, nesting depth, binding mode, and scenario
|
||||
/// to support various DI performance tests (singleton, factory, async, etc).
|
||||
class UniversalChainModule extends Module {
|
||||
/// Number of chains to create.
|
||||
final int chainCount;
|
||||
/// Depth of each chain.
|
||||
final int nestingDepth;
|
||||
/// How modules are registered (factory/singleton/async).
|
||||
final UniversalBindingMode bindingMode;
|
||||
/// Which di scenario to generate (chained, named, etc).
|
||||
final UniversalScenario scenario;
|
||||
|
||||
/// Constructs a configured test DI module for the benchmarks.
|
||||
UniversalChainModule({
|
||||
required this.chainCount,
|
||||
required this.nestingDepth,
|
||||
this.bindingMode = UniversalBindingMode.singletonStrategy,
|
||||
this.scenario = UniversalScenario.chain,
|
||||
});
|
||||
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
if (scenario == UniversalScenario.asyncChain) {
|
||||
// Generate async chain with singleton async bindings.
|
||||
for (var chainIndex = 0; chainIndex < chainCount; chainIndex++) {
|
||||
for (var levelIndex = 0; levelIndex < nestingDepth; levelIndex++) {
|
||||
final chain = chainIndex + 1;
|
||||
final level = levelIndex + 1;
|
||||
final prevDepName = '${chain}_${level - 1}';
|
||||
final depName = '${chain}_$level';
|
||||
bind<UniversalService>()
|
||||
.toProvideAsync(() async {
|
||||
final prev = level > 1
|
||||
? await currentScope.resolveAsync<UniversalService>(named: prevDepName)
|
||||
: null;
|
||||
return UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: prev,
|
||||
);
|
||||
})
|
||||
.withName(depName)
|
||||
.singleton();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
switch (scenario) {
|
||||
case UniversalScenario.register:
|
||||
// Simple singleton registration.
|
||||
bind<UniversalService>()
|
||||
.toProvide(() => UniversalServiceImpl(value: 'reg', dependency: null))
|
||||
.singleton();
|
||||
break;
|
||||
case UniversalScenario.named:
|
||||
// Named factory registration for two distinct objects.
|
||||
bind<UniversalService>().toProvide(() => UniversalServiceImpl(value: 'impl1')).withName('impl1');
|
||||
bind<UniversalService>().toProvide(() => UniversalServiceImpl(value: 'impl2')).withName('impl2');
|
||||
break;
|
||||
case UniversalScenario.chain:
|
||||
// Chain of nested services, with dependency on previous level by name.
|
||||
for (var chainIndex = 0; chainIndex < chainCount; chainIndex++) {
|
||||
for (var levelIndex = 0; levelIndex < nestingDepth; levelIndex++) {
|
||||
final chain = chainIndex + 1;
|
||||
final level = levelIndex + 1;
|
||||
final prevDepName = '${chain}_${level - 1}';
|
||||
final depName = '${chain}_$level';
|
||||
switch (bindingMode) {
|
||||
case UniversalBindingMode.singletonStrategy:
|
||||
bind<UniversalService>()
|
||||
.toProvide(() => UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: currentScope.tryResolve<UniversalService>(named: prevDepName),
|
||||
))
|
||||
.withName(depName)
|
||||
.singleton();
|
||||
break;
|
||||
case UniversalBindingMode.factoryStrategy:
|
||||
bind<UniversalService>()
|
||||
.toProvide(() => UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: currentScope.tryResolve<UniversalService>(named: prevDepName),
|
||||
))
|
||||
.withName(depName);
|
||||
break;
|
||||
case UniversalBindingMode.asyncStrategy:
|
||||
bind<UniversalService>()
|
||||
.toProvideAsync(() async => UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: await currentScope.resolveAsync<UniversalService>(named: prevDepName),
|
||||
))
|
||||
.withName(depName)
|
||||
.singleton();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Регистрация алиаса без имени (на последний элемент цепочки)
|
||||
final depName = '${chainCount}_$nestingDepth';
|
||||
bind<UniversalService>()
|
||||
.toProvide(() => currentScope.resolve<UniversalService>(named: depName))
|
||||
.singleton();
|
||||
break;
|
||||
case UniversalScenario.override:
|
||||
// handled at benchmark level, но алиас нужен прямо в этом scope!
|
||||
final depName = '${chainCount}_$nestingDepth';
|
||||
bind<UniversalService>()
|
||||
.toProvide(() => currentScope.resolve<UniversalService>(named: depName))
|
||||
.singleton();
|
||||
break;
|
||||
case UniversalScenario.asyncChain:
|
||||
// already handled above
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class CherrypickDIAdapter extends DIAdapter<Scope> {
|
||||
Scope? _scope;
|
||||
final bool _isSubScope;
|
||||
|
||||
CherrypickDIAdapter([Scope? scope, this._isSubScope = false]) {
|
||||
_scope = scope;
|
||||
}
|
||||
|
||||
@override
|
||||
void setupDependencies(void Function(Scope container) registration) {
|
||||
_scope ??= CherryPick.openRootScope();
|
||||
registration(_scope!);
|
||||
}
|
||||
|
||||
@override
|
||||
Registration<Scope> universalRegistration<S extends Enum>({
|
||||
required S scenario,
|
||||
required int chainCount,
|
||||
required int nestingDepth,
|
||||
required UniversalBindingMode bindingMode,
|
||||
}) {
|
||||
if (scenario is UniversalScenario) {
|
||||
return (scope) {
|
||||
scope.installModules([
|
||||
UniversalChainModule(
|
||||
chainCount: chainCount,
|
||||
nestingDepth: nestingDepth,
|
||||
bindingMode: bindingMode,
|
||||
scenario: scenario,
|
||||
),
|
||||
]);
|
||||
};
|
||||
}
|
||||
throw UnsupportedError('Scenario $scenario not supported by CherrypickDIAdapter');
|
||||
}
|
||||
|
||||
@override
|
||||
T resolve<T extends Object>({String? named}) =>
|
||||
_scope!.resolve<T>(named: named);
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync<T extends Object>({String? named}) async =>
|
||||
_scope!.resolveAsync<T>(named: named);
|
||||
|
||||
@override
|
||||
void teardown() {
|
||||
if (!_isSubScope) {
|
||||
CherryPick.closeRootScope();
|
||||
_scope = null;
|
||||
}
|
||||
// SubScope teardown не требуется
|
||||
}
|
||||
|
||||
@override
|
||||
CherrypickDIAdapter openSubScope(String name) {
|
||||
return CherrypickDIAdapter(_scope!.openSubScope(name), true);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> waitForAsyncReady() async {}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
import 'package:benchmark_di/scenarios/universal_binding_mode.dart';
|
||||
/// Универсальная абстракция для DI-адаптера с унифицированной функцией регистрации.
|
||||
/// Теперь для каждого адаптера задаём строгий generic тип контейнера.
|
||||
typedef Registration<TContainer> = void Function(TContainer);
|
||||
|
||||
abstract class DIAdapter<TContainer> {
|
||||
/// Устанавливает зависимости с помощью строго типизированного контейнера.
|
||||
void setupDependencies(void Function(TContainer container) registration);
|
||||
|
||||
/// Возвращает типобезопасную функцию регистрации зависимостей под конкретный сценарий.
|
||||
Registration<TContainer> universalRegistration<S extends Enum>({
|
||||
required S scenario,
|
||||
required int chainCount,
|
||||
required int nestingDepth,
|
||||
required UniversalBindingMode bindingMode,
|
||||
});
|
||||
|
||||
/// Резолвит (возвращает) экземпляр типа [T] (по имени, если требуется).
|
||||
T resolve<T extends Object>({String? named});
|
||||
|
||||
/// Асинхронно резолвит экземпляр типа [T] (если нужно).
|
||||
Future<T> resolveAsync<T extends Object>({String? named});
|
||||
|
||||
/// Уничтожает/отчищает DI-контейнер.
|
||||
void teardown();
|
||||
|
||||
/// Открывает дочерний scope и возвращает новый адаптер (если поддерживается).
|
||||
DIAdapter<TContainer> openSubScope(String name);
|
||||
|
||||
/// Ожидание готовности DI контейнера (если нужно для async DI).
|
||||
Future<void> waitForAsyncReady() async {}
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
import 'package:benchmark_di/scenarios/universal_binding_mode.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_scenario.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_service.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'di_adapter.dart';
|
||||
|
||||
/// Универсальный DIAdapter для GetIt c поддержкой scopes и строгой типизацией.
|
||||
class GetItAdapter extends DIAdapter<GetIt> {
|
||||
late GetIt _getIt;
|
||||
final String? _scopeName;
|
||||
final bool _isSubScope;
|
||||
bool _scopePushed = false;
|
||||
|
||||
/// Основной (root) и subScope-конструкторы.
|
||||
GetItAdapter({GetIt? instance, String? scopeName, bool isSubScope = false})
|
||||
: _scopeName = scopeName,
|
||||
_isSubScope = isSubScope {
|
||||
if (instance != null) {
|
||||
_getIt = instance;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void setupDependencies(void Function(GetIt container) registration) {
|
||||
if (_isSubScope) {
|
||||
// Создаём scope через pushNewScope с init
|
||||
_getIt.pushNewScope(
|
||||
scopeName: _scopeName,
|
||||
init: (getIt) => registration(getIt),
|
||||
);
|
||||
_scopePushed = true;
|
||||
} else {
|
||||
_getIt = GetIt.asNewInstance();
|
||||
registration(_getIt);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
T resolve<T extends Object>({String? named}) =>
|
||||
_getIt<T>(instanceName: named);
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync<T extends Object>({String? named}) async =>
|
||||
_getIt<T>(instanceName: named);
|
||||
|
||||
@override
|
||||
void teardown() {
|
||||
if (_isSubScope && _scopePushed) {
|
||||
_getIt.popScope();
|
||||
_scopePushed = false;
|
||||
} else {
|
||||
_getIt.reset();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
GetItAdapter openSubScope(String name) =>
|
||||
GetItAdapter(instance: _getIt, scopeName: name, isSubScope: true);
|
||||
|
||||
@override
|
||||
Future<void> waitForAsyncReady() async {
|
||||
await _getIt.allReady();
|
||||
}
|
||||
|
||||
@override
|
||||
Registration<GetIt> universalRegistration<S extends Enum>({
|
||||
required S scenario,
|
||||
required int chainCount,
|
||||
required int nestingDepth,
|
||||
required UniversalBindingMode bindingMode,
|
||||
}) {
|
||||
if (scenario is UniversalScenario) {
|
||||
return (getIt) {
|
||||
switch (scenario) {
|
||||
case UniversalScenario.asyncChain:
|
||||
for (int chain = 1; chain <= chainCount; chain++) {
|
||||
for (int level = 1; level <= nestingDepth; level++) {
|
||||
final prevDepName = '${chain}_${level - 1}';
|
||||
final depName = '${chain}_$level';
|
||||
getIt.registerSingletonAsync<UniversalService>(
|
||||
() async {
|
||||
final prev = level > 1
|
||||
? await getIt.getAsync<UniversalService>(instanceName: prevDepName)
|
||||
: null;
|
||||
return UniversalServiceImpl(value: depName, dependency: prev);
|
||||
},
|
||||
instanceName: depName,
|
||||
);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case UniversalScenario.register:
|
||||
getIt.registerSingleton<UniversalService>(UniversalServiceImpl(value: 'reg', dependency: null));
|
||||
break;
|
||||
case UniversalScenario.named:
|
||||
getIt.registerFactory<UniversalService>(() => UniversalServiceImpl(value: 'impl1'), instanceName: 'impl1');
|
||||
getIt.registerFactory<UniversalService>(() => UniversalServiceImpl(value: 'impl2'), instanceName: 'impl2');
|
||||
break;
|
||||
case UniversalScenario.chain:
|
||||
for (int chain = 1; chain <= chainCount; chain++) {
|
||||
for (int level = 1; level <= nestingDepth; level++) {
|
||||
final prevDepName = '${chain}_${level - 1}';
|
||||
final depName = '${chain}_$level';
|
||||
switch (bindingMode) {
|
||||
case UniversalBindingMode.singletonStrategy:
|
||||
getIt.registerSingleton<UniversalService>(
|
||||
UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: level > 1
|
||||
? getIt<UniversalService>(instanceName: prevDepName)
|
||||
: null,
|
||||
),
|
||||
instanceName: depName,
|
||||
);
|
||||
break;
|
||||
case UniversalBindingMode.factoryStrategy:
|
||||
getIt.registerFactory<UniversalService>(
|
||||
() => UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: level > 1
|
||||
? getIt<UniversalService>(instanceName: prevDepName)
|
||||
: null,
|
||||
),
|
||||
instanceName: depName,
|
||||
);
|
||||
break;
|
||||
case UniversalBindingMode.asyncStrategy:
|
||||
getIt.registerSingletonAsync<UniversalService>(
|
||||
() async => UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: level > 1
|
||||
? await getIt.getAsync<UniversalService>(instanceName: prevDepName)
|
||||
: null,
|
||||
),
|
||||
instanceName: depName,
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
case UniversalScenario.override:
|
||||
// handled at benchmark level
|
||||
break;
|
||||
}
|
||||
if (scenario == UniversalScenario.chain || scenario == UniversalScenario.override) {
|
||||
final depName = '${chainCount}_$nestingDepth';
|
||||
getIt.registerSingleton<UniversalService>(
|
||||
getIt<UniversalService>(instanceName: depName),
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
throw UnsupportedError('Scenario $scenario not supported by GetItAdapter');
|
||||
}
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
import 'package:benchmark_di/scenarios/universal_binding_mode.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_scenario.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_service.dart';
|
||||
import 'package:riverpod/riverpod.dart' as rp;
|
||||
import 'di_adapter.dart';
|
||||
|
||||
/// Унифицированный DIAdapter для Riverpod с поддержкой scopes и строгой типизацией.
|
||||
class RiverpodAdapter extends DIAdapter<Map<String, rp.ProviderBase<Object?>>> {
|
||||
rp.ProviderContainer? _container;
|
||||
final Map<String, rp.ProviderBase<Object?>> _namedProviders;
|
||||
final rp.ProviderContainer? _parent;
|
||||
|
||||
RiverpodAdapter({
|
||||
rp.ProviderContainer? container,
|
||||
Map<String, rp.ProviderBase<Object?>>? providers,
|
||||
rp.ProviderContainer? parent,
|
||||
bool isSubScope = false,
|
||||
}) : _container = container,
|
||||
_namedProviders = providers ?? <String, rp.ProviderBase<Object?>>{},
|
||||
_parent = parent;
|
||||
|
||||
@override
|
||||
void setupDependencies(void Function(Map<String, rp.ProviderBase<Object?>> container) registration) {
|
||||
_container ??= _parent == null
|
||||
? rp.ProviderContainer()
|
||||
: rp.ProviderContainer(parent: _parent);
|
||||
registration(_namedProviders);
|
||||
}
|
||||
|
||||
@override
|
||||
T resolve<T extends Object>({String? named}) {
|
||||
final key = named ?? T.toString();
|
||||
final provider = _namedProviders[key];
|
||||
if (provider == null) {
|
||||
throw Exception('Provider not found for $key');
|
||||
}
|
||||
return _container!.read(provider) as T;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync<T extends Object>({String? named}) async {
|
||||
final key = named ?? T.toString();
|
||||
final provider = _namedProviders[key];
|
||||
if (provider == null) {
|
||||
throw Exception('Provider not found for $key');
|
||||
}
|
||||
// Если это FutureProvider — используем .future
|
||||
if (provider.runtimeType.toString().contains('FutureProvider')) {
|
||||
return await _container!.read((provider as dynamic).future) as T;
|
||||
}
|
||||
return resolve<T>(named: named);
|
||||
}
|
||||
|
||||
@override
|
||||
void teardown() {
|
||||
_container?.dispose();
|
||||
_container = null;
|
||||
_namedProviders.clear();
|
||||
}
|
||||
|
||||
@override
|
||||
RiverpodAdapter openSubScope(String name) {
|
||||
final newContainer = rp.ProviderContainer(parent: _container);
|
||||
return RiverpodAdapter(
|
||||
container: newContainer,
|
||||
providers: Map.of(_namedProviders),
|
||||
parent: _container,
|
||||
isSubScope: true,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> waitForAsyncReady() async {
|
||||
// Riverpod синхронный по умолчанию.
|
||||
return;
|
||||
}
|
||||
|
||||
@override
|
||||
Registration<Map<String, rp.ProviderBase<Object?>>> universalRegistration<S extends Enum>({
|
||||
required S scenario,
|
||||
required int chainCount,
|
||||
required int nestingDepth,
|
||||
required UniversalBindingMode bindingMode,
|
||||
}) {
|
||||
if (scenario is UniversalScenario) {
|
||||
return (providers) {
|
||||
switch (scenario) {
|
||||
case UniversalScenario.register:
|
||||
providers['UniversalService'] = rp.Provider<UniversalService>((ref) => UniversalServiceImpl(value: 'reg', dependency: null));
|
||||
break;
|
||||
case UniversalScenario.named:
|
||||
providers['impl1'] = rp.Provider<UniversalService>((ref) => UniversalServiceImpl(value: 'impl1'));
|
||||
providers['impl2'] = rp.Provider<UniversalService>((ref) => UniversalServiceImpl(value: 'impl2'));
|
||||
break;
|
||||
case UniversalScenario.chain:
|
||||
for (int chain = 1; chain <= chainCount; chain++) {
|
||||
for (int level = 1; level <= nestingDepth; level++) {
|
||||
final prevDepName = '${chain}_${level - 1}';
|
||||
final depName = '${chain}_$level';
|
||||
providers[depName] = rp.Provider<UniversalService>((ref) => UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: level > 1 ? ref.watch(providers[prevDepName] as rp.ProviderBase<UniversalService>) : null,
|
||||
));
|
||||
}
|
||||
}
|
||||
final depName = '${chainCount}_$nestingDepth';
|
||||
providers['UniversalService'] = rp.Provider<UniversalService>((ref) => ref.watch(providers[depName] as rp.ProviderBase<UniversalService>));
|
||||
break;
|
||||
case UniversalScenario.override:
|
||||
// handled at benchmark level
|
||||
break;
|
||||
case UniversalScenario.asyncChain:
|
||||
for (int chain = 1; chain <= chainCount; chain++) {
|
||||
for (int level = 1; level <= nestingDepth; level++) {
|
||||
final prevDepName = '${chain}_${level - 1}';
|
||||
final depName = '${chain}_$level';
|
||||
providers[depName] = rp.FutureProvider<UniversalService>((ref) async {
|
||||
return UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: level > 1
|
||||
? await ref.watch((providers[prevDepName] as rp.FutureProvider<UniversalService>).future) as UniversalService?
|
||||
: null,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
final depName = '${chainCount}_$nestingDepth';
|
||||
providers['UniversalService'] = rp.FutureProvider<UniversalService>((ref) async {
|
||||
return await ref.watch((providers[depName] as rp.FutureProvider<UniversalService>).future);
|
||||
});
|
||||
break;
|
||||
}
|
||||
};
|
||||
}
|
||||
throw UnsupportedError('Scenario $scenario not supported by RiverpodAdapter');
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
/// Enum to represent the DI registration/binding mode.
|
||||
enum UniversalBindingMode {
|
||||
/// Singleton/provider binding.
|
||||
singletonStrategy,
|
||||
|
||||
/// Factory-based binding.
|
||||
factoryStrategy,
|
||||
|
||||
/// Async-based binding.
|
||||
asyncStrategy,
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
/// Enum to represent which scenario is constructed for the benchmark.
|
||||
enum UniversalScenario {
|
||||
/// Single registration.
|
||||
register,
|
||||
/// Chain of dependencies.
|
||||
chain,
|
||||
/// Named registrations.
|
||||
named,
|
||||
/// Child-scope override scenario.
|
||||
override,
|
||||
/// Asynchronous chain scenario.
|
||||
asyncChain,
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
|
||||
/// Base interface for any universal service in the benchmarks.
|
||||
///
|
||||
/// Represents an object in the dependency chain with an identifiable value
|
||||
/// and (optionally) a dependency on a previous service in the chain.
|
||||
abstract class UniversalService {
|
||||
/// String ID for this service instance (e.g. chain/level info).
|
||||
final String value;
|
||||
/// Optional reference to dependency service in the chain.
|
||||
final UniversalService? dependency;
|
||||
UniversalService({required this.value, this.dependency});
|
||||
}
|
||||
|
||||
/// Default implementation for [UniversalService] used in service chains.
|
||||
class UniversalServiceImpl extends UniversalService {
|
||||
UniversalServiceImpl({required super.value, super.dependency});
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="WEB_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/.dart_tool" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/.pub" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build" />
|
||||
</content>
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
<orderEntry type="library" name="Dart SDK" level="project" />
|
||||
<orderEntry type="library" name="Dart Packages" level="project" />
|
||||
</component>
|
||||
</module>
|
||||
@@ -1,132 +0,0 @@
|
||||
# Generated by pub
|
||||
# See https://dart.dev/tools/pub/glossary#lockfile
|
||||
packages:
|
||||
ansi_modifier:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: ansi_modifier
|
||||
sha256: "4b97c241f345e49c929bd56d0198b567b7dfcca7ec8d4f798745c9ced998684c"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.1.4"
|
||||
args:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: args
|
||||
sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.7.0"
|
||||
async:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: async
|
||||
sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.13.0"
|
||||
benchmark_harness:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: benchmark_harness
|
||||
sha256: "83f65107165883ba8623eb822daacb23dcf9f795c66841de758c9dd7c5a0cf28"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.3.1"
|
||||
benchmark_runner:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: benchmark_runner
|
||||
sha256: "7de181228eb74cb34507ded2260fe88b3b71e0aacfe0dfa794df49edaf041ca3"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.0.4"
|
||||
cherrypick:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "../cherrypick"
|
||||
relative: true
|
||||
source: path
|
||||
version: "3.0.0-dev.7"
|
||||
collection:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: collection
|
||||
sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.19.1"
|
||||
exception_templates:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: exception_templates
|
||||
sha256: "517f7c770da690073663f867ee2057ae2f4ffb28edae9da9faa624aa29ac76eb"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.3.1"
|
||||
get_it:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: get_it
|
||||
sha256: a4292e7cf67193f8e7c1258203104eb2a51ec8b3a04baa14695f4064c144297b
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "8.2.0"
|
||||
lazy_memo:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: lazy_memo
|
||||
sha256: dcb30b4184a6d767e1d779d74ce784d752d38313b8fb4bad6b659ae7af4bb34d
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.2.3"
|
||||
lints:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: lints
|
||||
sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.1.1"
|
||||
meta:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: meta
|
||||
sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.17.0"
|
||||
path:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path
|
||||
sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.9.1"
|
||||
riverpod:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: riverpod
|
||||
sha256: "59062512288d3056b2321804332a13ffdd1bf16df70dcc8e506e411280a72959"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.6.1"
|
||||
stack_trace:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: stack_trace
|
||||
sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.12.1"
|
||||
state_notifier:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: state_notifier
|
||||
sha256: b8677376aa54f2d7c58280d5a007f9e8774f1968d1fb1c096adcb4792fba29bb
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.0"
|
||||
sdks:
|
||||
dart: ">=3.6.0 <4.0.0"
|
||||
@@ -1,19 +0,0 @@
|
||||
name: benchmark_di
|
||||
version: 0.1.0
|
||||
publish_to: none
|
||||
description: Universal benchmark for any DI library (cherrypick, get_it, and others)
|
||||
|
||||
environment:
|
||||
sdk: '>=3.0.0 <4.0.0'
|
||||
|
||||
dependencies:
|
||||
cherrypick:
|
||||
path: ../cherrypick
|
||||
args: ^2.7.0
|
||||
get_it: ^8.2.0
|
||||
riverpod: ^2.6.1
|
||||
|
||||
dev_dependencies:
|
||||
lints: ^5.0.0
|
||||
benchmark_harness: ^2.2.2
|
||||
benchmark_runner: ^0.0.2
|
||||
@@ -1,74 +1,3 @@
|
||||
## 3.0.0-dev.8
|
||||
|
||||
- **REFACTOR**(tests): replace MockLogger with MockObserver in scope tests to align with updated observer API.
|
||||
- **FIX**(doc): remove hide symbol.
|
||||
- **FEAT**(core): add full DI lifecycle observability via onInstanceDisposed.
|
||||
- **DOCS**(logging): update Logging section in README with modern Observer usage and Talker integration examples.
|
||||
- **DOCS**(observer): improve documentation, translate all comments to English, add usage examples.
|
||||
- **DOCS**(README): add section with overview table for additional modules.
|
||||
- **DOCS**(README): refactor structure and improve clarity of advanced features.
|
||||
- **DOCS**(README): add 'Hierarchical Subscopes' section and update structure for advanced features clarity.
|
||||
|
||||
## 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.
|
||||
- **PERF**(scope): speed up dependency lookup with Map-based binding resolver index.
|
||||
- **DOCS**(perf): clarify Map-based resolver optimization applies since v3.0.0 in all docs.
|
||||
- **DOCS**: update EN/RU quick start and tutorial with Fast Map-based lookup section; clarify performance benefit in README.
|
||||
|
||||
## 3.0.0-dev.4
|
||||
|
||||
- **REFACTOR**(scope): simplify _findBindingResolver<T> with one-liner and optional chaining.
|
||||
- **PERF**(scope): speed up dependency lookup with Map-based binding resolver index.
|
||||
- **DOCS**(perf): clarify Map-based resolver optimization applies since v3.0.0 in all docs.
|
||||
- **DOCS**: update EN/RU quick start and tutorial with Fast Map-based lookup section; clarify performance benefit in README.
|
||||
|
||||
## 3.0.0-dev.3
|
||||
|
||||
- **REFACTOR**(scope): simplify _findBindingResolver<T> with one-liner and optional chaining.
|
||||
- **PERF**(scope): speed up dependency lookup with Map-based binding resolver index.
|
||||
- **DOCS**(perf): clarify Map-based resolver optimization applies since v3.0.0 in all docs.
|
||||
- **DOCS**: update EN/RU quick start and tutorial with Fast Map-based lookup section; clarify performance benefit in README.
|
||||
|
||||
## 3.0.0-dev.2
|
||||
|
||||
> Note: This release has breaking changes.
|
||||
|
||||
- **FEAT**(binding): add deprecated proxy async methods for backward compatibility and highlight transition to modern API.
|
||||
- **DOCS**: add quick guide for circular dependency detection to README.
|
||||
- **DOCS**: add quick guide for circular dependency detection to README.
|
||||
- **BREAKING** **FEAT**: implement comprehensive circular dependency detection system.
|
||||
- **BREAKING** **FEAT**: implement comprehensive circular dependency detection system.
|
||||
|
||||
## 3.0.0-dev.1
|
||||
|
||||
- **DOCS**: add quick guide for circular dependency detection to README.
|
||||
|
||||
## 3.0.0-dev.0
|
||||
|
||||
> Note: This release has breaking changes.
|
||||
|
||||
@@ -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
|
||||
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
http://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,
|
||||
|
||||
@@ -1,103 +1,19 @@
|
||||
# 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.
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
- [Key Features](#key-features)
|
||||
- [Installation](#installation)
|
||||
- [Getting Started](#getting-started)
|
||||
- [Core Concepts](#core-concepts)
|
||||
- [Binding](#binding)
|
||||
- [Module](#module)
|
||||
- [Scope](#scope)
|
||||
- [Disposable](#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)
|
||||
- [Additional Modules](#additional-modules)
|
||||
- [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
|
||||
## Key Concepts
|
||||
|
||||
### Binding
|
||||
|
||||
A **Binding** acts as a configuration for how to create or provide a particular dependency. Bindings support:
|
||||
|
||||
* Direct instance assignment (`toInstance()`, `toInstanceAsync()`)
|
||||
* Lazy providers (sync/async functions)
|
||||
* Provider functions supporting dynamic parameters
|
||||
* Named instances for resolving by string key
|
||||
* Optional singleton lifecycle
|
||||
|
||||
- Direct instance assignment (`toInstance()`, `toInstanceAsync()`)
|
||||
- Lazy providers (sync/async functions)
|
||||
- Provider functions supporting dynamic parameters
|
||||
- Named instances for resolving by string key
|
||||
- Optional singleton lifecycle
|
||||
|
||||
#### Example
|
||||
|
||||
@@ -164,67 +80,22 @@ final str = rootScope.resolve<String>();
|
||||
// Resolve a dependency asynchronously
|
||||
final result = await rootScope.resolveAsync<String>();
|
||||
|
||||
// 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();
|
||||
// Close the root scope once done
|
||||
CherryPick.closeRootScope();
|
||||
```
|
||||
|
||||
---
|
||||
#### Working with Subscopes
|
||||
|
||||
### 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!');
|
||||
}
|
||||
}
|
||||
// Open a named child scope (e.g., for a feature/module)
|
||||
final subScope = rootScope.openSubScope('featureScope')
|
||||
..installModules([FeatureModule()]);
|
||||
|
||||
final scope = CherryPick.openRootScope();
|
||||
scope.installModules([
|
||||
Module((bind) => bind<CacheManager>().toProvide(() => CacheManager()).singleton()),
|
||||
]);
|
||||
|
||||
// ...later
|
||||
await CherryPick.closeRootScope(); // prints: CacheManager disposed!
|
||||
// Resolve from subScope, with fallback to parents if missing
|
||||
final dataBloc = await subScope.resolveAsync<DataBloc>();
|
||||
```
|
||||
|
||||
#### 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.
|
||||
|
||||
---
|
||||
|
||||
## Dependency Resolution API
|
||||
### Dependency Lookup API
|
||||
|
||||
- `resolve<T>()` — Locates a dependency instance or throws if missing.
|
||||
- `resolveAsync<T>()` — Async variant for dependencies requiring async binding.
|
||||
@@ -236,335 +107,6 @@ Supports:
|
||||
- Named dependencies
|
||||
- Provider functions with and without runtime parameters
|
||||
|
||||
---
|
||||
|
||||
## 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 `_ProfilePage` 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.
|
||||
|
||||
---
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### Hierarchical Subscopes
|
||||
|
||||
CherryPick supports a hierarchical structure of scopes, allowing you to create complex and modular dependency graphs for advanced application architectures. Each subscope inherits from its parent, enabling context-specific overrides while still allowing access to global or shared services.
|
||||
|
||||
#### Key Points
|
||||
|
||||
- **Subscopes** are child scopes that can be opened from any existing scope (including the root).
|
||||
- Dependencies registered in a subscope override those from parent scopes when resolved.
|
||||
- If a dependency is not found in the current subscope, the resolution process automatically searches parent scopes up the hierarchy.
|
||||
- Subscopes can have their own modules, lifetime, and disposable objects.
|
||||
- You can nest subscopes to any depth, modeling features, flows, or components independently.
|
||||
|
||||
#### Example
|
||||
|
||||
```dart
|
||||
final rootScope = CherryPick.openRootScope();
|
||||
rootScope.installModules([AppModule()]);
|
||||
|
||||
// Open a hierarchical subscope for a feature or page
|
||||
final userFeatureScope = rootScope.openSubScope('userFeature');
|
||||
userFeatureScope.installModules([UserFeatureModule()]);
|
||||
|
||||
// Dependencies defined in UserFeatureModule will take precedence
|
||||
final userService = userFeatureScope.resolve<UserService>();
|
||||
|
||||
// If not found in the subscope, lookup continues in the parent (rootScope)
|
||||
final sharedService = userFeatureScope.resolve<SharedService>();
|
||||
|
||||
// You can nest subscopes
|
||||
final dialogScope = userFeatureScope.openSubScope('dialog');
|
||||
dialogScope.installModules([DialogModule()]);
|
||||
final dialogManager = dialogScope.resolve<DialogManager>();
|
||||
```
|
||||
|
||||
#### Use Cases
|
||||
|
||||
- Isolate feature modules, flows, or screens with their own dependencies.
|
||||
- Provide and override services for specific navigation stacks or platform-specific branches.
|
||||
- Manage the lifetime and disposal of groups of dependencies independently (e.g., per-user, per-session, per-component).
|
||||
|
||||
**Tip:** Always close subscopes when they are no longer needed to release resources and trigger cleanup of Disposable dependencies.
|
||||
|
||||
---
|
||||
|
||||
### Logging
|
||||
|
||||
CherryPick lets you log all dependency injection (DI) events and errors using a flexible observer mechanism.
|
||||
|
||||
#### Custom Observers
|
||||
|
||||
You can pass any implementation of `CherryPickObserver` to your root scope or any sub-scope.
|
||||
This allows centralized and extensible logging, which you can direct to print, files, visualization frameworks, external loggers, or systems like [Talker](https://pub.dev/packages/talker).
|
||||
|
||||
##### Example: Printing All Events
|
||||
|
||||
```dart
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
void main() {
|
||||
// Use the built-in PrintCherryPickObserver for console logs
|
||||
final observer = PrintCherryPickObserver();
|
||||
final scope = CherryPick.openRootScope(observer: observer);
|
||||
// All DI actions and errors will now be printed!
|
||||
}
|
||||
```
|
||||
|
||||
##### Example: Advanced Logging with Talker
|
||||
|
||||
For richer logging, analytics, or UI overlays, use an advanced observer such as [talker_cherrypick_logger](../talker_cherrypick_logger):
|
||||
|
||||
```dart
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:talker/talker.dart';
|
||||
import 'package:talker_cherrypick_logger/talker_cherrypick_logger.dart';
|
||||
|
||||
void main() {
|
||||
final talker = Talker();
|
||||
final observer = TalkerCherryPickObserver(talker);
|
||||
CherryPick.openRootScope(observer: observer);
|
||||
// All container events go to the Talker log system!
|
||||
}
|
||||
```
|
||||
|
||||
#### Default Behavior
|
||||
|
||||
- By default, logging is silent (`SilentCherryPickObserver`) for production, with no output unless you supply an observer.
|
||||
- You can configure observers **per scope** for isolated, test-specific, or feature-specific logging.
|
||||
|
||||
#### Observer Capabilities
|
||||
|
||||
Events you can observe and log:
|
||||
- Dependency registration
|
||||
- Instance requests, creations, disposals
|
||||
- Module installs/removals
|
||||
- Scope opening/closing
|
||||
- Cache hits/misses
|
||||
- Cycle detection
|
||||
- Diagnostics, warnings, errors
|
||||
|
||||
Just implement or extend `CherryPickObserver` and direct messages anywhere you want!
|
||||
|
||||
#### When to Use
|
||||
|
||||
- Enable verbose logging and debugging in development or test builds.
|
||||
- Route logs to your main log system or analytics.
|
||||
- Hook into DI lifecycle for profiling or monitoring.
|
||||
|
||||
|
||||
---
|
||||
|
||||
### Circular Dependency Detection
|
||||
|
||||
CherryPick can detect circular dependencies in your DI configuration, helping you avoid infinite loops and hard-to-debug errors.
|
||||
|
||||
**How to use:**
|
||||
|
||||
#### 1. Enable Cycle Detection for Development
|
||||
|
||||
**Local detection (within one scope):**
|
||||
```dart
|
||||
final scope = CherryPick.openSafeRootScope(); // Local detection enabled by default
|
||||
// or, for an existing scope:
|
||||
scope.enableCycleDetection();
|
||||
```
|
||||
|
||||
**Global detection (across all scopes):**
|
||||
```dart
|
||||
CherryPick.enableGlobalCrossScopeCycleDetection();
|
||||
final rootScope = CherryPick.openGlobalSafeRootScope();
|
||||
```
|
||||
|
||||
#### 2. Error Example
|
||||
|
||||
If you declare mutually dependent services:
|
||||
```dart
|
||||
class A { A(B b); }
|
||||
class B { B(A a); }
|
||||
|
||||
scope.installModules([
|
||||
Module((bind) {
|
||||
bind<A>().to((s) => A(s.resolve<B>()));
|
||||
bind<B>().to((s) => B(s.resolve<A>()));
|
||||
}),
|
||||
]);
|
||||
|
||||
scope.resolve<A>(); // Throws CircularDependencyException
|
||||
```
|
||||
|
||||
#### 3. Typical Usage Pattern
|
||||
|
||||
- **Always enable detection** in debug and test environments for maximum safety.
|
||||
- **Disable detection** in production for performance (after code is tested).
|
||||
|
||||
```dart
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
void main() {
|
||||
if (kDebugMode) {
|
||||
CherryPick.enableGlobalCycleDetection();
|
||||
CherryPick.enableGlobalCrossScopeCycleDetection();
|
||||
}
|
||||
runApp(MyApp());
|
||||
}
|
||||
```
|
||||
|
||||
#### 4. Handling and Debugging Errors
|
||||
|
||||
On detection, `CircularDependencyException` is thrown with a readable dependency chain:
|
||||
```dart
|
||||
try {
|
||||
scope.resolve<MyService>();
|
||||
} on CircularDependencyException catch (e) {
|
||||
print('Dependency chain: ${e.dependencyChain}');
|
||||
}
|
||||
```
|
||||
|
||||
**More details:** See [cycle_detection.en.md](doc/cycle_detection.en.md)
|
||||
|
||||
---
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
> **Performance Note:**
|
||||
> **Starting from version 3.0.0**, CherryPick uses a Map-based resolver index for dependency lookup. This means calls to `resolve<T>()` and related methods are now O(1) operations, regardless of the number of modules or bindings in your scope. Previously, the library had to iterate over all modules and bindings to locate the requested dependency, which could impact performance as your project grew.
|
||||
>
|
||||
> This optimization is internal and does not change any library APIs or usage patterns, but it significantly improves resolution speed in larger applications.
|
||||
|
||||
---
|
||||
|
||||
## Example Application
|
||||
|
||||
Below is a complete example illustrating modules, subscopes, async providers, and dependency resolution.
|
||||
@@ -686,51 +228,34 @@ class ApiClientImpl implements ApiClient {
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Features
|
||||
|
||||
## FAQ
|
||||
- [x] Main Scope and Named Subscopes
|
||||
- [x] Named Instance Binding and Resolution
|
||||
- [x] Asynchronous and Synchronous Providers
|
||||
- [x] Providers Supporting Runtime Parameters
|
||||
- [x] Singleton Lifecycle Management
|
||||
- [x] Modular and Hierarchical Composition
|
||||
- [x] Null-safe Resolution (tryResolve/tryResolveAsync)
|
||||
- [x] Circular Dependency Detection (Local and Global)
|
||||
|
||||
### Q: Do I need to use `await` with CherryPick.closeRootScope(), CherryPick.closeScope(), or scope.dispose() if I have no Disposable services?
|
||||
## Documentation
|
||||
|
||||
**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 Links
|
||||
|
||||
* Circular Dependency Detection [(En)](doc/cycle_detection.en.md)[(Ru)](doc/cycle_detection.ru.md)
|
||||
|
||||
---
|
||||
|
||||
## Additional Modules
|
||||
|
||||
CherryPick provides a set of official add-on modules for advanced use cases and specific platforms:
|
||||
|
||||
| Module name | Description | Documentation |
|
||||
|-------------|-------------|---------------|
|
||||
| [**cherrypick_annotations**](https://pub.dev/packages/cherrypick_annotations) | Dart annotations for concise DI definitions and code generation. | [README](../cherrypick_annotations/README.md) |
|
||||
| [**cherrypick_generator**](https://pub.dev/packages/cherrypick_generator) | Code generator to produce DI bindings based on annotations. | [README](../cherrypick_generator/README.md) |
|
||||
| [**cherrypick_flutter**](https://pub.dev/packages/cherrypick_flutter) | Flutter integration: DI provider widgets and helpers for Flutter. | [README](../cherrypick_flutter/README.md) |
|
||||
|
||||
---
|
||||
- [Circular Dependency Detection (English)](doc/cycle_detection.en.md)
|
||||
- [Обнаружение циклических зависимостей (Русский)](doc/cycle_detection.ru.md)
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions are welcome! Please open issues or submit pull requests on [GitHub](https://github.com/pese-git/cherrypick).
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
Licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0).
|
||||
Licensed under the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).
|
||||
|
||||
---
|
||||
|
||||
**Important:** 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 specific language governing permissions and limitations under the License.
|
||||
|
||||
---
|
||||
|
||||
## Links
|
||||
|
||||
- [GitHub Repository](https://github.com/pese-git/cherrypick)
|
||||
- [GitHub Repository](https://github.com/pese-git/cherrypick)
|
||||
@@ -17,28 +17,19 @@ class FeatureModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
// Using toProvideAsync for async initialization
|
||||
bind<DataRepository>()
|
||||
.withName("networkRepo")
|
||||
.toProvideWithParams((params) async {
|
||||
print('REPO PARAMS: $params');
|
||||
|
||||
bind<DataRepository>().withName("networkRepo").toProvideAsync(() async {
|
||||
final client = await Future.delayed(
|
||||
Duration(milliseconds: 1000),
|
||||
() => currentScope.resolve<ApiClient>(
|
||||
named: isMock ? "apiClientMock" : "apiClientImpl",
|
||||
),
|
||||
);
|
||||
|
||||
Duration(milliseconds: 100),
|
||||
() => currentScope.resolve<ApiClient>(
|
||||
named: isMock ? "apiClientMock" : "apiClientImpl"));
|
||||
return NetworkDataRepository(client);
|
||||
}).singleton();
|
||||
|
||||
// Asynchronous initialization of DataBloc
|
||||
bind<DataBloc>().toProvide(
|
||||
bind<DataBloc>().toProvideAsync(
|
||||
() async {
|
||||
final repo = await currentScope.resolveAsync<DataRepository>(
|
||||
named: "networkRepo",
|
||||
params: 'Some params',
|
||||
);
|
||||
named: "networkRepo");
|
||||
return DataBloc(repo);
|
||||
},
|
||||
);
|
||||
@@ -47,19 +38,18 @@ class FeatureModule extends Module {
|
||||
|
||||
Future<void> main() async {
|
||||
try {
|
||||
final scope = CherryPick.openRootScope().installModules([AppModule()]);
|
||||
final scope = openRootScope().installModules([
|
||||
AppModule(),
|
||||
]);
|
||||
|
||||
final subScope = scope
|
||||
.openSubScope("featureScope")
|
||||
.installModules([FeatureModule(isMock: true)]);
|
||||
|
||||
// Asynchronous instance resolution
|
||||
final dataBloc = await subScope.resolveAsync<DataBloc>();
|
||||
dataBloc.data.listen(
|
||||
(d) => print('Received data: $d'),
|
||||
onError: (e) => print('Error: $e'),
|
||||
onDone: () => print('DONE'),
|
||||
);
|
||||
// Asynchronous instance resolution
|
||||
final dataBloc = await subScope.resolveAsync<DataBloc>();
|
||||
dataBloc.data.listen((d) => print('Received data: $d'),
|
||||
onError: (e) => print('Error: $e'), onDone: () => print('DONE'));
|
||||
|
||||
await dataBloc.fetchData();
|
||||
} catch (e) {
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
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.setGlobalObserver(PrintCherryPickObserver());
|
||||
|
||||
// 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.setGlobalObserver(SilentCherryPickObserver());
|
||||
rootScope.resolve<UserRepository>(); // now without logs
|
||||
}
|
||||
@@ -126,7 +126,7 @@ void main() {
|
||||
// Example 1: Demonstrate circular dependency
|
||||
print('1. Attempt to create a scope with circular dependencies:');
|
||||
try {
|
||||
final scope = CherryPick.openRootScope();
|
||||
final scope = Scope(null);
|
||||
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 = CherryPick.openRootScope();
|
||||
final scope = Scope(null);
|
||||
// НЕ включаем обнаружение циклических зависимостей
|
||||
|
||||
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 = CherryPick.openRootScope();
|
||||
final scope = Scope(null);
|
||||
scope.enableCycleDetection(); // Включаем для безопасности
|
||||
|
||||
scope.installModules([
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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,12 +13,9 @@ library;
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
export 'package:cherrypick/src/binding_resolver.dart';
|
||||
export 'package:cherrypick/src/binding.dart';
|
||||
export 'package:cherrypick/src/cycle_detector.dart';
|
||||
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/disposable.dart';
|
||||
export 'package:cherrypick/src/observer.dart';
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
@@ -11,76 +11,44 @@
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:cherrypick/src/binding_resolver.dart';
|
||||
enum Mode { simple, instance, providerInstance, providerInstanceWithParams }
|
||||
|
||||
/// RU: Класс Binding<T> настраивает параметры экземпляра.
|
||||
/// ENG: The Binding<T> class configures the settings for the instance.
|
||||
typedef Provider<T> = T? Function();
|
||||
|
||||
typedef ProviderWithParams<T> = T Function(dynamic params);
|
||||
|
||||
typedef AsyncProvider<T> = Future<T> Function();
|
||||
|
||||
typedef AsyncProviderWithParams<T> = Future<T> Function(dynamic params);
|
||||
|
||||
/// RU: Класс Binding<T> настраивает параметры экземпляра.
|
||||
/// ENG: The Binding<T> class configures the settings for the instance.
|
||||
///
|
||||
import 'package:cherrypick/src/observer.dart';
|
||||
|
||||
class Binding<T> {
|
||||
late Mode _mode;
|
||||
late Type _key;
|
||||
String? _name;
|
||||
late String _name;
|
||||
T? _instance;
|
||||
Future<T>? _instanceAsync;
|
||||
Provider<T>? _provider;
|
||||
ProviderWithParams<T>? _providerWithParams;
|
||||
|
||||
BindingResolver<T>? _resolver;
|
||||
AsyncProvider<T>? asyncProvider;
|
||||
AsyncProviderWithParams<T>? asyncProviderWithParams;
|
||||
|
||||
CherryPickObserver? observer;
|
||||
late bool _isSingleton = false;
|
||||
late bool _isNamed = false;
|
||||
|
||||
// Deferred logging flags
|
||||
bool _createdLogged = false;
|
||||
bool _namedLogged = false;
|
||||
bool _singletonLogged = false;
|
||||
|
||||
Binding({this.observer}) {
|
||||
Binding() {
|
||||
_mode = Mode.simple;
|
||||
_key = T;
|
||||
// Deferred уведомения observer, не логировать здесь напрямую
|
||||
}
|
||||
|
||||
void markCreated() {
|
||||
if (!_createdLogged) {
|
||||
observer?.onBindingRegistered(
|
||||
runtimeType.toString(),
|
||||
T,
|
||||
);
|
||||
_createdLogged = true;
|
||||
}
|
||||
}
|
||||
|
||||
void markNamed() {
|
||||
if (isNamed && !_namedLogged) {
|
||||
observer?.onDiagnostic(
|
||||
'Binding named: ${T.toString()} name: $_name',
|
||||
details: {
|
||||
'type': 'Binding',
|
||||
'name': T.toString(),
|
||||
'nameParam': _name,
|
||||
'description': 'named',
|
||||
},
|
||||
);
|
||||
_namedLogged = true;
|
||||
}
|
||||
}
|
||||
|
||||
void markSingleton() {
|
||||
if (isSingleton && !_singletonLogged) {
|
||||
observer?.onDiagnostic(
|
||||
'Binding singleton: ${T.toString()}${_name != null ? ' name: $_name' : ''}',
|
||||
details: {
|
||||
'type': 'Binding',
|
||||
'name': T.toString(),
|
||||
if (_name != null) 'name': _name,
|
||||
'description': 'singleton mode enabled',
|
||||
},
|
||||
);
|
||||
_singletonLogged = true;
|
||||
}
|
||||
}
|
||||
|
||||
void logAllDeferred() {
|
||||
markCreated();
|
||||
markNamed();
|
||||
markSingleton();
|
||||
}
|
||||
/// RU: Метод возвращает [Mode] экземпляра.
|
||||
/// ENG: The method returns the [Mode] of the instance.
|
||||
///
|
||||
/// return [Mode]
|
||||
Mode get mode => _mode;
|
||||
|
||||
/// RU: Метод возвращает тип экземпляра.
|
||||
/// ENG: The method returns the type of the instance.
|
||||
@@ -92,21 +60,19 @@ class Binding<T> {
|
||||
/// ENG: The method returns the name of the instance.
|
||||
///
|
||||
/// return [String]
|
||||
String? get name => _name;
|
||||
|
||||
/// RU: Метод проверяет именован экземпляр или нет.
|
||||
/// ENG: The method checks whether the instance is named or not.
|
||||
///
|
||||
/// return [bool]
|
||||
bool get isNamed => _name != null;
|
||||
String get name => _name;
|
||||
|
||||
/// RU: Метод проверяет сингелтон экземпляр или нет.
|
||||
/// ENG: The method checks the singleton instance or not.
|
||||
///
|
||||
/// return [bool]
|
||||
bool get isSingleton => _resolver?.isSingleton ?? false;
|
||||
bool get isSingleton => _isSingleton;
|
||||
|
||||
BindingResolver<T>? get resolver => _resolver;
|
||||
/// RU: Метод проверяет именован экземпляр или нет.
|
||||
/// ENG: The method checks whether the instance is named or not.
|
||||
///
|
||||
/// return [bool]
|
||||
bool get isNamed => _isNamed;
|
||||
|
||||
/// RU: Добавляет имя для экземляпя [value].
|
||||
/// ENG: Added name for instance [value].
|
||||
@@ -114,7 +80,7 @@ class Binding<T> {
|
||||
/// return [Binding]
|
||||
Binding<T> withName(String name) {
|
||||
_name = name;
|
||||
// Не логируем здесь, deferred log via markNamed()
|
||||
_isNamed = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -122,8 +88,21 @@ class Binding<T> {
|
||||
/// ENG: Initialization instance [value].
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toInstance(Instance<T> value) {
|
||||
_resolver = InstanceResolver<T>(value);
|
||||
Binding<T> toInstance(T value) {
|
||||
_mode = Mode.instance;
|
||||
_instance = value;
|
||||
_isSingleton = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Инициализация экземляпяра [value].
|
||||
/// ENG: Initialization instance [value].
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toInstanceAsync(Future<T> value) {
|
||||
_mode = Mode.instance;
|
||||
_instanceAsync = value;
|
||||
_isSingleton = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -132,7 +111,18 @@ class Binding<T> {
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toProvide(Provider<T> value) {
|
||||
_resolver = ProviderResolver<T>((_) => value.call(), withParams: false);
|
||||
_mode = Mode.providerInstance;
|
||||
_provider = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Инициализация экземляпяра через провайдер [value].
|
||||
/// ENG: Initialization instance via provider [value].
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toProvideAsync(AsyncProvider<T> provider) {
|
||||
_mode = Mode.providerInstance;
|
||||
asyncProvider = provider;
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -141,23 +131,19 @@ class Binding<T> {
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toProvideWithParams(ProviderWithParams<T> value) {
|
||||
_resolver = ProviderResolver<T>(value, withParams: true);
|
||||
_mode = Mode.providerInstanceWithParams;
|
||||
_providerWithParams = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Deprecated('Use toInstance instead of toInstanceAsync')
|
||||
Binding<T> toInstanceAsync(Instance<T> value) {
|
||||
return this.toInstance(value);
|
||||
}
|
||||
|
||||
@Deprecated('Use toProvide instead of toProvideAsync')
|
||||
Binding<T> toProvideAsync(Provider<T> value) {
|
||||
return this.toProvide(value);
|
||||
}
|
||||
|
||||
@Deprecated('Use toProvideWithParams instead of toProvideAsyncWithParams')
|
||||
Binding<T> toProvideAsyncWithParams(ProviderWithParams<T> value) {
|
||||
return this.toProvideWithParams(value);
|
||||
/// RU: Инициализация экземляра через асинхронный провайдер [value] с динамическим параметром.
|
||||
/// ENG: Initializes the instance via async provider [value] with a dynamic param.
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toProvideAsyncWithParams(AsyncProviderWithParams<T> provider) {
|
||||
_mode = Mode.providerInstanceWithParams;
|
||||
asyncProviderWithParams = provider;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Инициализация экземляпяра как сингелтон [value].
|
||||
@@ -165,62 +151,40 @@ class Binding<T> {
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> singleton() {
|
||||
_resolver?.toSingleton();
|
||||
// Не логируем здесь, deferred log via markSingleton()
|
||||
_isSingleton = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
T? resolveSync([dynamic params]) {
|
||||
final res = resolver?.resolveSync(params);
|
||||
if (res != null) {
|
||||
observer?.onDiagnostic(
|
||||
'Binding resolved instance: ${T.toString()}',
|
||||
details: {
|
||||
if (_name != null) 'name': _name,
|
||||
'method': 'resolveSync',
|
||||
'description': 'object created/resolved',
|
||||
},
|
||||
);
|
||||
} else {
|
||||
observer?.onWarning(
|
||||
'resolveSync returned null: ${T.toString()}',
|
||||
details: {
|
||||
if (_name != null) 'name': _name,
|
||||
'method': 'resolveSync',
|
||||
'description': 'resolveSync returned null',
|
||||
},
|
||||
);
|
||||
/// RU: Поиск экземпляра.
|
||||
/// ENG: Resolve instance.
|
||||
///
|
||||
/// return [T]
|
||||
T? get instance => _instance;
|
||||
|
||||
/// RU: Поиск экземпляра.
|
||||
/// ENG: Resolve instance.
|
||||
///
|
||||
/// return [T]
|
||||
Future<T>? get instanceAsync => _instanceAsync;
|
||||
|
||||
/// RU: Поиск экземпляра.
|
||||
/// ENG: Resolve instance.
|
||||
///
|
||||
/// return [T]
|
||||
T? get provider {
|
||||
if (_isSingleton) {
|
||||
_instance ??= _provider?.call();
|
||||
return _instance;
|
||||
}
|
||||
return res;
|
||||
return _provider?.call();
|
||||
}
|
||||
|
||||
Future<T>? resolveAsync([dynamic params]) {
|
||||
final future = resolver?.resolveAsync(params);
|
||||
if (future != null) {
|
||||
future
|
||||
.then((res) => observer?.onDiagnostic(
|
||||
'Future resolved for: ${T.toString()}',
|
||||
details: {
|
||||
if (_name != null) 'name': _name,
|
||||
'method': 'resolveAsync',
|
||||
'description': 'Future resolved',
|
||||
},
|
||||
))
|
||||
.catchError((e, s) => observer?.onError(
|
||||
'resolveAsync error: ${T.toString()}',
|
||||
e,
|
||||
s,
|
||||
));
|
||||
} else {
|
||||
observer?.onWarning(
|
||||
'resolveAsync returned null: ${T.toString()}',
|
||||
details: {
|
||||
if (_name != null) 'name': _name,
|
||||
'method': 'resolveAsync',
|
||||
'description': 'resolveAsync returned null',
|
||||
},
|
||||
);
|
||||
}
|
||||
return future;
|
||||
/// RU: Поиск экземпляра с параметром.
|
||||
///
|
||||
/// ENG: Resolve instance with [params].
|
||||
///
|
||||
/// return [T]
|
||||
T? providerWithParams(dynamic params) {
|
||||
return _providerWithParams?.call(params);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
//
|
||||
// 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>;
|
||||
|
||||
/// RU: Синхронный или асинхронный провайдер без параметров, возвращающий [T] или [Future<T>].
|
||||
/// ENG: Synchronous or asynchronous provider without parameters, returning [T] or [Future<T>].
|
||||
typedef Provider<T> = FutureOr<T> Function();
|
||||
|
||||
/// RU: Провайдер с динамическим параметром, возвращающий [T] или [Future<T>] в зависимости от реализации.
|
||||
/// ENG: Provider with dynamic parameter, returning [T] or [Future<T>] depending on implementation.
|
||||
typedef ProviderWithParams<T> = FutureOr<T> Function(dynamic);
|
||||
|
||||
/// RU: Абстрактный интерфейс для классов, которые разрешают зависимости типа [T].
|
||||
/// ENG: Abstract interface for classes that resolve dependencies of type [T].
|
||||
abstract class BindingResolver<T> {
|
||||
/// RU: Синхронное разрешение зависимости с параметром [params].
|
||||
/// ENG: Synchronous resolution of the dependency with [params].
|
||||
T? resolveSync([dynamic params]);
|
||||
|
||||
/// RU: Асинхронное разрешение зависимости с параметром [params].
|
||||
/// ENG: Asynchronous resolution of the dependency with [params].
|
||||
Future<T>? resolveAsync([dynamic params]);
|
||||
|
||||
/// RU: Помечает текущий резолвер как синглтон — результат будет закеширован.
|
||||
/// ENG: Marks this resolver as singleton — result will be cached.
|
||||
void toSingleton();
|
||||
|
||||
bool get isSingleton;
|
||||
}
|
||||
|
||||
/// RU: Резолвер, оборачивающий конкретный экземпляр [T] (или Future<T>), без вызова провайдера.
|
||||
/// ENG: Resolver that wraps a concrete instance of [T] (or Future<T>), without provider invocation.
|
||||
class InstanceResolver<T> implements BindingResolver<T> {
|
||||
final Instance<T> _instance;
|
||||
|
||||
/// RU: Создаёт резолвер, оборачивающий значение [instance].
|
||||
/// ENG: Creates a resolver that wraps the given [instance].
|
||||
InstanceResolver(this._instance);
|
||||
|
||||
@override
|
||||
T resolveSync([_]) {
|
||||
if (_instance is T) return _instance;
|
||||
throw StateError(
|
||||
'Instance $_instance is Future; '
|
||||
'use resolveAsync() instead',
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync([_]) {
|
||||
if (_instance is Future<T>) return _instance;
|
||||
|
||||
return Future.value(_instance);
|
||||
}
|
||||
|
||||
@override
|
||||
void toSingleton() {}
|
||||
|
||||
@override
|
||||
bool get isSingleton => true;
|
||||
}
|
||||
|
||||
/// RU: Резолвер, оборачивающий провайдер, с возможностью синглтон-кеширования.
|
||||
/// ENG: Resolver that wraps a provider, with optional singleton caching.
|
||||
class ProviderResolver<T> implements BindingResolver<T> {
|
||||
final ProviderWithParams<T> _provider;
|
||||
final bool _withParams;
|
||||
|
||||
FutureOr<T>? _cache;
|
||||
bool _singleton = false;
|
||||
|
||||
/// RU: Создаёт резолвер из произвольной функции [raw], поддерживающей ноль или один параметр.
|
||||
/// ENG: Creates a resolver from arbitrary function [raw], supporting zero or one parameter.
|
||||
ProviderResolver(
|
||||
ProviderWithParams<T> provider, {
|
||||
required bool withParams,
|
||||
}) : _provider = provider,
|
||||
_withParams = withParams;
|
||||
|
||||
@override
|
||||
T resolveSync([dynamic params]) {
|
||||
_checkParams(params);
|
||||
|
||||
final result = _cache ?? _provider(params);
|
||||
|
||||
if (result is T) {
|
||||
if (_singleton) {
|
||||
_cache ??= result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
throw StateError(
|
||||
'Provider [$_provider] return Future<$T>. Use resolveAsync() instead.',
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync([dynamic params]) {
|
||||
_checkParams(params);
|
||||
|
||||
final result = _cache ?? _provider(params);
|
||||
final target = result is Future<T> ? result : Future<T>.value(result);
|
||||
|
||||
if (_singleton) {
|
||||
_cache ??= target;
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
@override
|
||||
void toSingleton() {
|
||||
_singleton = true;
|
||||
}
|
||||
|
||||
@override
|
||||
bool get isSingleton => _singleton;
|
||||
|
||||
/// RU: Проверяет, был ли передан параметр, если провайдер требует его.
|
||||
/// ENG: Checks if parameter is passed when the provider expects it.
|
||||
void _checkParams(dynamic params) {
|
||||
if (_withParams && params == null) {
|
||||
throw StateError(
|
||||
'[$T] Params is null. Maybe you forgot to pass it?',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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,7 +12,6 @@
|
||||
//
|
||||
|
||||
import 'dart:collection';
|
||||
import 'package:cherrypick/src/observer.dart';
|
||||
|
||||
/// RU: Исключение, выбрасываемое при обнаружении циклической зависимости.
|
||||
/// ENG: Exception thrown when a circular dependency is detected.
|
||||
@@ -20,10 +19,7 @@ class CircularDependencyException implements Exception {
|
||||
final String message;
|
||||
final List<String> dependencyChain;
|
||||
|
||||
CircularDependencyException(this.message, this.dependencyChain) {
|
||||
// DEBUG
|
||||
|
||||
}
|
||||
const CircularDependencyException(this.message, this.dependencyChain);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
@@ -35,36 +31,24 @@ class CircularDependencyException implements Exception {
|
||||
/// RU: Детектор циклических зависимостей для CherryPick DI контейнера.
|
||||
/// ENG: Circular dependency detector for CherryPick DI container.
|
||||
class CycleDetector {
|
||||
final CherryPickObserver _observer;
|
||||
// Стек текущих разрешаемых зависимостей
|
||||
final Set<String> _resolutionStack = HashSet<String>();
|
||||
|
||||
// История разрешения для построения цепочки зависимостей
|
||||
final List<String> _resolutionHistory = [];
|
||||
|
||||
CycleDetector({required CherryPickObserver observer}) : _observer = observer;
|
||||
|
||||
/// RU: Начинает отслеживание разрешения зависимости.
|
||||
/// ENG: Starts tracking dependency resolution.
|
||||
///
|
||||
/// Throws [CircularDependencyException] if circular dependency is detected.
|
||||
void startResolving<T>({String? named}) {
|
||||
final dependencyKey = _createDependencyKey<T>(named);
|
||||
_observer.onDiagnostic(
|
||||
'CycleDetector startResolving: $dependencyKey',
|
||||
details: {
|
||||
'event': 'startResolving',
|
||||
'stackSize': _resolutionStack.length,
|
||||
},
|
||||
);
|
||||
|
||||
if (_resolutionStack.contains(dependencyKey)) {
|
||||
// Найдена циклическая зависимость
|
||||
final cycleStartIndex = _resolutionHistory.indexOf(dependencyKey);
|
||||
final cycle = _resolutionHistory.sublist(cycleStartIndex)..add(dependencyKey);
|
||||
_observer.onCycleDetected(
|
||||
cycle,
|
||||
);
|
||||
_observer.onError(
|
||||
'Cycle detected for $dependencyKey',
|
||||
null,
|
||||
null,
|
||||
);
|
||||
|
||||
throw CircularDependencyException(
|
||||
'Circular dependency detected for $dependencyKey',
|
||||
cycle,
|
||||
@@ -79,11 +63,8 @@ class CycleDetector {
|
||||
/// ENG: Finishes tracking dependency resolution.
|
||||
void finishResolving<T>({String? named}) {
|
||||
final dependencyKey = _createDependencyKey<T>(named);
|
||||
_observer.onDiagnostic(
|
||||
'CycleDetector finishResolving: $dependencyKey',
|
||||
details: {'event': 'finishResolving'},
|
||||
);
|
||||
_resolutionStack.remove(dependencyKey);
|
||||
|
||||
// Удаляем из истории только если это последний элемент
|
||||
if (_resolutionHistory.isNotEmpty &&
|
||||
_resolutionHistory.last == dependencyKey) {
|
||||
@@ -94,13 +75,6 @@ class CycleDetector {
|
||||
/// RU: Очищает все состояние детектора.
|
||||
/// ENG: Clears all detector state.
|
||||
void clear() {
|
||||
_observer.onDiagnostic(
|
||||
'CycleDetector clear',
|
||||
details: {
|
||||
'event': 'clear',
|
||||
'description': 'resolution stack cleared',
|
||||
},
|
||||
);
|
||||
_resolutionStack.clear();
|
||||
_resolutionHistory.clear();
|
||||
}
|
||||
@@ -128,32 +102,17 @@ class CycleDetector {
|
||||
/// ENG: Mixin for adding circular dependency detection support.
|
||||
mixin CycleDetectionMixin {
|
||||
CycleDetector? _cycleDetector;
|
||||
CherryPickObserver get observer;
|
||||
|
||||
/// RU: Включает обнаружение циклических зависимостей.
|
||||
/// ENG: Enables circular dependency detection.
|
||||
void enableCycleDetection() {
|
||||
_cycleDetector = CycleDetector(observer: observer);
|
||||
observer.onDiagnostic(
|
||||
'CycleDetection enabled',
|
||||
details: {
|
||||
'event': 'enable',
|
||||
'description': 'cycle detection enabled',
|
||||
},
|
||||
);
|
||||
_cycleDetector = CycleDetector();
|
||||
}
|
||||
|
||||
/// RU: Отключает обнаружение циклических зависимостей.
|
||||
/// ENG: Disables circular dependency detection.
|
||||
void disableCycleDetection() {
|
||||
_cycleDetector?.clear();
|
||||
observer.onDiagnostic(
|
||||
'CycleDetection disabled',
|
||||
details: {
|
||||
'event': 'disable',
|
||||
'description': 'cycle detection disabled',
|
||||
},
|
||||
);
|
||||
_cycleDetector = null;
|
||||
}
|
||||
|
||||
@@ -180,14 +139,7 @@ mixin CycleDetectionMixin {
|
||||
final cycleStartIndex = _cycleDetector!._resolutionHistory.indexOf(dependencyKey);
|
||||
final cycle = _cycleDetector!._resolutionHistory.sublist(cycleStartIndex)
|
||||
..add(dependencyKey);
|
||||
observer.onCycleDetected(
|
||||
cycle,
|
||||
);
|
||||
observer.onError(
|
||||
'Cycle detected for $dependencyKey',
|
||||
null,
|
||||
null,
|
||||
);
|
||||
|
||||
throw CircularDependencyException(
|
||||
'Circular dependency detected for $dependencyKey',
|
||||
cycle,
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
//
|
||||
// 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();
|
||||
}
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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,15 +12,12 @@
|
||||
//
|
||||
|
||||
import 'dart:collection';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
import 'package:cherrypick/src/cycle_detector.dart';
|
||||
|
||||
/// RU: Глобальный детектор циклических зависимостей для всей иерархии скоупов.
|
||||
/// ENG: Global circular dependency detector for entire scope hierarchy.
|
||||
class GlobalCycleDetector {
|
||||
static GlobalCycleDetector? _instance;
|
||||
|
||||
final CherryPickObserver _observer;
|
||||
|
||||
// Глобальный стек разрешения зависимостей
|
||||
final Set<String> _globalResolutionStack = HashSet<String>();
|
||||
@@ -31,12 +28,12 @@ class GlobalCycleDetector {
|
||||
// Карта активных детекторов по скоупам
|
||||
final Map<String, CycleDetector> _scopeDetectors = HashMap<String, CycleDetector>();
|
||||
|
||||
GlobalCycleDetector._internal({required CherryPickObserver observer}): _observer = observer;
|
||||
GlobalCycleDetector._internal();
|
||||
|
||||
/// RU: Получить единственный экземпляр глобального детектора.
|
||||
/// ENG: Get singleton instance of global detector.
|
||||
static GlobalCycleDetector get instance {
|
||||
_instance ??= GlobalCycleDetector._internal(observer: CherryPick.globalObserver);
|
||||
_instance ??= GlobalCycleDetector._internal();
|
||||
return _instance!;
|
||||
}
|
||||
|
||||
@@ -58,15 +55,7 @@ class GlobalCycleDetector {
|
||||
// Найдена глобальная циклическая зависимость
|
||||
final cycleStartIndex = _globalResolutionHistory.indexOf(dependencyKey);
|
||||
final cycle = _globalResolutionHistory.sublist(cycleStartIndex)..add(dependencyKey);
|
||||
_observer.onCycleDetected(
|
||||
cycle,
|
||||
scopeName: scopeId,
|
||||
);
|
||||
_observer.onError(
|
||||
'Global circular dependency detected for $dependencyKey',
|
||||
null,
|
||||
null,
|
||||
);
|
||||
|
||||
throw CircularDependencyException(
|
||||
'Global circular dependency detected for $dependencyKey',
|
||||
cycle,
|
||||
@@ -104,15 +93,7 @@ class GlobalCycleDetector {
|
||||
final cycleStartIndex = _globalResolutionHistory.indexOf(dependencyKey);
|
||||
final cycle = _globalResolutionHistory.sublist(cycleStartIndex)
|
||||
..add(dependencyKey);
|
||||
_observer.onCycleDetected(
|
||||
cycle,
|
||||
scopeName: scopeId,
|
||||
);
|
||||
_observer.onError(
|
||||
'Global circular dependency detected for $dependencyKey',
|
||||
null,
|
||||
null,
|
||||
);
|
||||
|
||||
throw CircularDependencyException(
|
||||
'Global circular dependency detected for $dependencyKey',
|
||||
cycle,
|
||||
@@ -136,7 +117,7 @@ class GlobalCycleDetector {
|
||||
/// RU: Получить детектор для конкретного скоупа.
|
||||
/// ENG: Get detector for specific scope.
|
||||
CycleDetector getScopeDetector(String scopeId) {
|
||||
return _scopeDetectors.putIfAbsent(scopeId, () => CycleDetector(observer: CherryPick.globalObserver));
|
||||
return _scopeDetectors.putIfAbsent(scopeId, () => CycleDetector());
|
||||
}
|
||||
|
||||
/// RU: Удалить детектор для скоупа.
|
||||
|
||||
@@ -3,120 +3,77 @@
|
||||
// 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
|
||||
// http://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/observer.dart';
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
|
||||
Scope? _rootScope;
|
||||
|
||||
/// Global logger for all [Scope]s managed by [CherryPick].
|
||||
///
|
||||
/// Defaults to [SilentLogger] unless set via [setGlobalLogger].
|
||||
CherryPickObserver _globalObserver = SilentCherryPickObserver();
|
||||
|
||||
/// 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 {
|
||||
/// Sets the global logger for all [Scope]s created by CherryPick.
|
||||
/// RU: Метод открывает главный [Scope].
|
||||
/// ENG: The method opens the main [Scope].
|
||||
///
|
||||
/// Allows customizing log output and DI diagnostics globally.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.setGlobalLogger(DefaultLogger());
|
||||
/// ```
|
||||
static void setGlobalObserver(CherryPickObserver observer) {
|
||||
_globalObserver = observer;
|
||||
}
|
||||
|
||||
/// Returns the current global logger used by CherryPick.
|
||||
static CherryPickObserver get globalObserver => _globalObserver;
|
||||
|
||||
/// Returns the singleton root [Scope], creating it if needed.
|
||||
///
|
||||
/// Applies configured [globalLogger] and cycle detection settings.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final root = CherryPick.openRootScope();
|
||||
/// ```
|
||||
/// return
|
||||
static Scope openRootScope() {
|
||||
_rootScope ??= Scope(null, observer: _globalObserver);
|
||||
// Apply cycle detection settings
|
||||
_rootScope ??= Scope(null);
|
||||
|
||||
// Применяем глобальную настройку обнаружения циклических зависимостей
|
||||
if (_globalCycleDetectionEnabled && !_rootScope!.isCycleDetectionEnabled) {
|
||||
_rootScope!.enableCycleDetection();
|
||||
}
|
||||
|
||||
// Применяем глобальную настройку обнаружения между скоупами
|
||||
if (_globalCrossScopeCycleDetectionEnabled && !_rootScope!.isGlobalCycleDetectionEnabled) {
|
||||
_rootScope!.enableGlobalCycleDetection();
|
||||
}
|
||||
|
||||
return _rootScope!;
|
||||
}
|
||||
|
||||
/// Disposes and resets the root [Scope] singleton.
|
||||
/// RU: Метод закрывает главный [Scope].
|
||||
/// ENG: The method close the main [Scope].
|
||||
///
|
||||
/// Call before tests or when needing full re-initialization.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.closeRootScope();
|
||||
/// ```
|
||||
static Future<void> closeRootScope() async {
|
||||
static void closeRootScope() {
|
||||
if (_rootScope != null) {
|
||||
await _rootScope!.dispose(); // Автоматический вызов dispose для rootScope!
|
||||
_rootScope = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Globally enables cycle detection for all new [Scope]s created by CherryPick.
|
||||
/// RU: Глобально включает обнаружение циклических зависимостей для всех новых скоупов.
|
||||
/// ENG: Globally enables circular dependency detection for all new scopes.
|
||||
///
|
||||
/// Strongly recommended for safety in all projects.
|
||||
/// Этот метод влияет на все скоупы, создаваемые через CherryPick.
|
||||
/// This method affects all scopes created through CherryPick.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.enableGlobalCycleDetection();
|
||||
/// final scope = CherryPick.openRootScope(); // Автоматически включено обнаружение
|
||||
/// ```
|
||||
static void enableGlobalCycleDetection() {
|
||||
_globalCycleDetectionEnabled = true;
|
||||
|
||||
// Включаем для уже существующего root scope, если он есть
|
||||
if (_rootScope != null) {
|
||||
_rootScope!.enableCycleDetection();
|
||||
}
|
||||
}
|
||||
|
||||
/// Disables global local cycle detection. Existing and new scopes won't check for local cycles.
|
||||
/// RU: Глобально отключает обнаружение циклических зависимостей.
|
||||
/// ENG: Globally disables circular dependency detection.
|
||||
///
|
||||
/// Рекомендуется использовать в production для максимальной производительности.
|
||||
/// Recommended for production use for maximum performance.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
@@ -124,63 +81,85 @@ class CherryPick {
|
||||
/// ```
|
||||
static void disableGlobalCycleDetection() {
|
||||
_globalCycleDetectionEnabled = false;
|
||||
|
||||
// Отключаем для уже существующего root scope, если он есть
|
||||
if (_rootScope != null) {
|
||||
_rootScope!.disableCycleDetection();
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if global local cycle detection is enabled.
|
||||
/// RU: Проверяет, включено ли глобальное обнаружение циклических зависимостей.
|
||||
/// ENG: Checks if global circular dependency detection is enabled.
|
||||
///
|
||||
/// return true если включено, false если отключено
|
||||
/// return true if enabled, false if disabled
|
||||
static bool get isGlobalCycleDetectionEnabled => _globalCycleDetectionEnabled;
|
||||
|
||||
/// Enables cycle detection for a particular scope tree.
|
||||
/// RU: Включает обнаружение циклических зависимостей для конкретного скоупа.
|
||||
/// ENG: Enables circular dependency detection for a specific scope.
|
||||
///
|
||||
/// [scopeName] - hierarchical string path (e.g. 'feature.api'), or empty for root.
|
||||
/// [separator] - path separator (default: '.'), e.g. '/' for "feature/api/module"
|
||||
/// [scopeName] - имя скоупа (пустая строка для root scope)
|
||||
/// [scopeName] - scope name (empty string for root scope)
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.enableCycleDetectionForScope(scopeName: 'api.feature');
|
||||
/// CherryPick.enableCycleDetectionForScope(); // Для root scope
|
||||
/// CherryPick.enableCycleDetectionForScope(scopeName: 'feature.auth'); // Для конкретного scope
|
||||
/// ```
|
||||
static void enableCycleDetectionForScope({String scopeName = '', String separator = '.'}) {
|
||||
final scope = _getScope(scopeName, separator);
|
||||
scope.enableCycleDetection();
|
||||
}
|
||||
|
||||
/// Disables cycle detection for a given scope. See [enableCycleDetectionForScope].
|
||||
/// RU: Отключает обнаружение циклических зависимостей для конкретного скоупа.
|
||||
/// ENG: Disables circular dependency detection for a specific scope.
|
||||
///
|
||||
/// [scopeName] - имя скоупа (пустая строка для root scope)
|
||||
/// [scopeName] - scope name (empty string for root scope)
|
||||
static void disableCycleDetectionForScope({String scopeName = '', String separator = '.'}) {
|
||||
final scope = _getScope(scopeName, separator);
|
||||
scope.disableCycleDetection();
|
||||
}
|
||||
|
||||
/// Returns `true` if cycle detection is enabled for the requested scope.
|
||||
/// RU: Проверяет, включено ли обнаружение циклических зависимостей для конкретного скоупа.
|
||||
/// ENG: Checks if circular dependency detection is enabled for a specific scope.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.isCycleDetectionEnabledForScope(scopeName: 'feature.api');
|
||||
/// ```
|
||||
/// [scopeName] - имя скоупа (пустая строка для root scope)
|
||||
/// [scopeName] - scope name (empty string for root scope)
|
||||
///
|
||||
/// return true если включено, false если отключено
|
||||
/// return true if enabled, false if disabled
|
||||
static bool isCycleDetectionEnabledForScope({String scopeName = '', String separator = '.'}) {
|
||||
final scope = _getScope(scopeName, separator);
|
||||
return scope.isCycleDetectionEnabled;
|
||||
}
|
||||
|
||||
/// Returns the current dependency resolution chain inside the given scope.
|
||||
/// RU: Возвращает текущую цепочку разрешения зависимостей для конкретного скоупа.
|
||||
/// ENG: Returns current dependency resolution chain for a specific scope.
|
||||
///
|
||||
/// Useful for diagnostics (to print what types are currently resolving).
|
||||
/// Полезно для отладки и анализа зависимостей.
|
||||
/// Useful for debugging and dependency analysis.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// print(CherryPick.getCurrentResolutionChain(scopeName: 'feature.api'));
|
||||
/// ```
|
||||
/// [scopeName] - имя скоупа (пустая строка для root scope)
|
||||
/// [scopeName] - scope name (empty string for root scope)
|
||||
///
|
||||
/// return список имен зависимостей в текущей цепочке разрешения
|
||||
/// return list of dependency names in current resolution chain
|
||||
static List<String> getCurrentResolutionChain({String scopeName = '', String separator = '.'}) {
|
||||
final scope = _getScope(scopeName, separator);
|
||||
return scope.currentResolutionChain;
|
||||
}
|
||||
|
||||
/// Opens the root scope and enables local cycle detection.
|
||||
/// RU: Создает новый скоуп с автоматически включенным обнаружением циклических зависимостей.
|
||||
/// ENG: Creates a new scope with automatically enabled circular dependency detection.
|
||||
///
|
||||
/// Удобный метод для создания безопасных скоупов в development режиме.
|
||||
/// Convenient method for creating safe scopes in development mode.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final safeRoot = CherryPick.openSafeRootScope();
|
||||
/// final scope = CherryPick.openSafeRootScope();
|
||||
/// // Обнаружение циклических зависимостей автоматически включено
|
||||
/// ```
|
||||
static Scope openSafeRootScope() {
|
||||
final scope = openRootScope();
|
||||
@@ -188,11 +167,16 @@ class CherryPick {
|
||||
return scope;
|
||||
}
|
||||
|
||||
/// Opens a named/nested scope and enables local cycle detection for it.
|
||||
/// RU: Создает новый дочерний скоуп с автоматически включенным обнаружением циклических зависимостей.
|
||||
/// ENG: Creates a new child scope with automatically enabled circular dependency detection.
|
||||
///
|
||||
/// [scopeName] - имя скоупа
|
||||
/// [scopeName] - scope name
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final api = CherryPick.openSafeScope(scopeName: 'feature.api');
|
||||
/// final scope = CherryPick.openSafeScope(scopeName: 'feature.auth');
|
||||
/// // Обнаружение циклических зависимостей автоматически включено
|
||||
/// ```
|
||||
static Scope openSafeScope({String scopeName = '', String separator = '.'}) {
|
||||
final scope = openScope(scopeName: scopeName, separator: separator);
|
||||
@@ -200,8 +184,8 @@ class CherryPick {
|
||||
return scope;
|
||||
}
|
||||
|
||||
/// Returns a [Scope] by path (or the root if none specified).
|
||||
/// Used for internal diagnostics & helpers.
|
||||
/// RU: Внутренний метод для получения скоупа по имени.
|
||||
/// ENG: Internal method to get scope by name.
|
||||
static Scope _getScope(String scopeName, String separator) {
|
||||
if (scopeName.isEmpty) {
|
||||
return openRootScope();
|
||||
@@ -209,76 +193,91 @@ class CherryPick {
|
||||
return openScope(scopeName: scopeName, separator: separator);
|
||||
}
|
||||
|
||||
/// Opens (and creates nested subscopes if needed) a scope by hierarchical path.
|
||||
/// RU: Метод открывает дочерний [Scope].
|
||||
/// ENG: The method open the child [Scope].
|
||||
///
|
||||
/// [scopeName] - dot-separated path ("api.feature"). Empty = root.
|
||||
/// [separator] - path delimiter (default: '.')
|
||||
///
|
||||
/// Applies global cycle detection settings to the returned scope.
|
||||
/// Дочерний [Scope] открывается с [scopeName]
|
||||
/// Child [Scope] open with [scopeName]
|
||||
///
|
||||
/// 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 previous, String element) => previous.openSubScope(element)
|
||||
);
|
||||
openRootScope(),
|
||||
(Scope previousValue, String element) =>
|
||||
previousValue.openSubScope(element));
|
||||
|
||||
// Применяем глобальную настройку обнаружения циклических зависимостей
|
||||
if (_globalCycleDetectionEnabled && !scope.isCycleDetectionEnabled) {
|
||||
scope.enableCycleDetection();
|
||||
}
|
||||
|
||||
// Применяем глобальную настройку обнаружения между скоупами
|
||||
if (_globalCrossScopeCycleDetectionEnabled && !scope.isGlobalCycleDetectionEnabled) {
|
||||
scope.enableGlobalCycleDetection();
|
||||
}
|
||||
|
||||
return scope;
|
||||
}
|
||||
|
||||
/// Closes a named or root scope (if [scopeName] is omitted).
|
||||
/// RU: Метод открывает дочерний [Scope].
|
||||
/// ENG: The method open the child [Scope].
|
||||
///
|
||||
/// [scopeName] - dot-separated hierarchical path (e.g. 'api.feature'). Empty = root.
|
||||
/// [separator] - path delimiter.
|
||||
/// Дочерний [Scope] открывается с [scopeName]
|
||||
/// Child [Scope] open with [scopeName]
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.closeScope(scopeName: 'network.super.api');
|
||||
/// ```
|
||||
/// final String scopeName = 'firstScope.secondScope';
|
||||
/// final subScope = CherryPick.closeScope(scopeName);
|
||||
/// ```
|
||||
///
|
||||
///
|
||||
@experimental
|
||||
static Future<void> closeScope({String scopeName = '', String separator = '.'}) async {
|
||||
static void closeScope({String scopeName = '', String separator = '.'}) {
|
||||
if (scopeName.isEmpty) {
|
||||
await closeRootScope();
|
||||
return;
|
||||
closeRootScope();
|
||||
}
|
||||
|
||||
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 previous, String element) => previous.openSubScope(element)
|
||||
);
|
||||
await scope.closeSubScope(lastPart);
|
||||
openRootScope(),
|
||||
(Scope previousValue, String element) =>
|
||||
previousValue.openSubScope(element));
|
||||
scope.closeSubScope(lastPart);
|
||||
} else {
|
||||
await openRootScope().closeSubScope(nameParts.first);
|
||||
openRootScope().closeSubScope(nameParts[0]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Enables cross-scope cycle detection globally.
|
||||
/// RU: Глобально включает обнаружение циклических зависимостей между скоупами.
|
||||
/// ENG: Globally enables cross-scope circular dependency detection.
|
||||
///
|
||||
/// 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.
|
||||
/// Этот режим обнаруживает циклические зависимости во всей иерархии скоупов.
|
||||
/// This mode detects circular dependencies across the entire scope hierarchy.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
@@ -286,15 +285,15 @@ class CherryPick {
|
||||
/// ```
|
||||
static void enableGlobalCrossScopeCycleDetection() {
|
||||
_globalCrossScopeCycleDetectionEnabled = true;
|
||||
|
||||
// Включаем для уже существующего root scope, если он есть
|
||||
if (_rootScope != null) {
|
||||
_rootScope!.enableGlobalCycleDetection();
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// RU: Глобально отключает обнаружение циклических зависимостей между скоупами.
|
||||
/// ENG: Globally disables cross-scope circular dependency detection.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
@@ -302,55 +301,54 @@ class CherryPick {
|
||||
/// ```
|
||||
static void disableGlobalCrossScopeCycleDetection() {
|
||||
_globalCrossScopeCycleDetectionEnabled = false;
|
||||
|
||||
// Отключаем для уже существующего root scope, если он есть
|
||||
if (_rootScope != null) {
|
||||
_rootScope!.disableGlobalCycleDetection();
|
||||
}
|
||||
|
||||
// Очищаем глобальный детектор
|
||||
GlobalCycleDetector.instance.clear();
|
||||
}
|
||||
|
||||
/// Returns `true` if global cross-scope cycle detection is enabled.
|
||||
/// RU: Проверяет, включено ли глобальное обнаружение циклических зависимостей между скоупами.
|
||||
/// ENG: Checks if global cross-scope circular dependency detection is enabled.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// if (CherryPick.isGlobalCrossScopeCycleDetectionEnabled) {
|
||||
/// print('Global cross-scope detection is ON');
|
||||
/// }
|
||||
/// ```
|
||||
/// return true если включено, false если отключено
|
||||
/// return true if enabled, false if disabled
|
||||
static bool get isGlobalCrossScopeCycleDetectionEnabled => _globalCrossScopeCycleDetectionEnabled;
|
||||
|
||||
/// Returns the current global dependency resolution chain (across all scopes).
|
||||
/// RU: Возвращает глобальную цепочку разрешения зависимостей.
|
||||
/// ENG: Returns global dependency resolution chain.
|
||||
///
|
||||
/// Shows the cross-scope resolution stack, which is useful for advanced diagnostics
|
||||
/// and debugging cycle issues that occur between scopes.
|
||||
/// Полезно для отладки циклических зависимостей между скоупами.
|
||||
/// Useful for debugging circular dependencies across scopes.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// print(CherryPick.getGlobalResolutionChain());
|
||||
/// ```
|
||||
/// return список имен зависимостей в глобальной цепочке разрешения
|
||||
/// return list of dependency names in global resolution chain
|
||||
static List<String> getGlobalResolutionChain() {
|
||||
return GlobalCycleDetector.instance.globalResolutionChain;
|
||||
}
|
||||
|
||||
/// Clears the global cross-scope cycle detector.
|
||||
/// RU: Очищает все состояние глобального детектора циклических зависимостей.
|
||||
/// ENG: Clears all global circular dependency detector state.
|
||||
///
|
||||
/// Useful in tests or when resetting application state.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.clearGlobalCycleDetector();
|
||||
/// ```
|
||||
/// Полезно для тестов и сброса состояния.
|
||||
/// Useful for tests and state reset.
|
||||
static void clearGlobalCycleDetector() {
|
||||
GlobalCycleDetector.reset();
|
||||
}
|
||||
|
||||
/// Opens the root scope with both local and global cross-scope cycle detection enabled.
|
||||
/// RU: Создает новый скоуп с автоматически включенным глобальным обнаружением циклических зависимостей.
|
||||
/// ENG: Creates a new scope with automatically enabled global circular dependency detection.
|
||||
///
|
||||
/// This is the safest way to start IoC for most apps — cycles will be detected
|
||||
/// both inside a single scope and between scopes.
|
||||
/// Этот скоуп будет отслеживать циклические зависимости во всей иерархии.
|
||||
/// This scope will track circular dependencies across the entire hierarchy.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final root = CherryPick.openGlobalSafeRootScope();
|
||||
/// final scope = CherryPick.openGlobalSafeRootScope();
|
||||
/// // Глобальное обнаружение циклических зависимостей автоматически включено
|
||||
/// ```
|
||||
static Scope openGlobalSafeRootScope() {
|
||||
final scope = openRootScope();
|
||||
@@ -359,13 +357,16 @@ class CherryPick {
|
||||
return scope;
|
||||
}
|
||||
|
||||
/// Opens the given named/nested scope and enables both local and cross-scope cycle detection on it.
|
||||
/// RU: Создает новый дочерний скоуп с автоматически включенным глобальным обнаружением циклических зависимостей.
|
||||
/// ENG: Creates a new child scope with automatically enabled global circular dependency detection.
|
||||
///
|
||||
/// Recommended when creating feature/module scopes in large apps.
|
||||
/// [scopeName] - имя скоупа
|
||||
/// [scopeName] - scope name
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final featureScope = CherryPick.openGlobalSafeScope(scopeName: 'featureA.api');
|
||||
/// final scope = CherryPick.openGlobalSafeScope(scopeName: 'feature.auth');
|
||||
/// // Глобальное обнаружение циклических зависимостей автоматически включено
|
||||
/// ```
|
||||
static Scope openGlobalSafeScope({String scopeName = '', String separator = '.'}) {
|
||||
final scope = openScope(scopeName: scopeName, separator: separator);
|
||||
@@ -373,4 +374,4 @@ class CherryPick {
|
||||
scope.enableGlobalCycleDetection();
|
||||
return scope;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -1,236 +0,0 @@
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
|
||||
/// An abstract Observer for CherryPick DI container events.
|
||||
///
|
||||
/// Extend this class to react to and log various events inside the CherryPick Dependency Injection container.
|
||||
/// Allows monitoring of registration, creation, disposal, module changes, cache hits/misses, cycles, and
|
||||
/// errors/warnings for improved diagnostics and debugging.
|
||||
///
|
||||
/// All methods have detailed event information, including name, type, scope, and other arguments.
|
||||
///
|
||||
/// Example: Logging and debugging container events
|
||||
/// ```dart
|
||||
/// final CherryPickObserver observer = PrintCherryPickObserver();
|
||||
/// // Pass observer to CherryPick during setup
|
||||
/// CherryPick.openRootScope(observer: observer);
|
||||
/// ```
|
||||
abstract class CherryPickObserver {
|
||||
// === Registration and instance lifecycle ===
|
||||
/// Called when a binding is registered within the container (new dependency mapping).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onBindingRegistered('MyService', MyService, scopeName: 'root');
|
||||
/// ```
|
||||
void onBindingRegistered(String name, Type type, {String? scopeName});
|
||||
|
||||
/// Called when an instance is requested (before it is created or retrieved from cache).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onInstanceRequested('MyService', MyService, scopeName: 'root');
|
||||
/// ```
|
||||
void onInstanceRequested(String name, Type type, {String? scopeName});
|
||||
|
||||
/// Called when a new instance is successfully created.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onInstanceCreated('MyService', MyService, instance, scopeName: 'root');
|
||||
/// ```
|
||||
void onInstanceCreated(String name, Type type, Object instance, {String? scopeName});
|
||||
|
||||
/// Called when an instance is disposed (removed from cache and/or finalized).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onInstanceDisposed('MyService', MyService, instance, scopeName: 'root');
|
||||
/// ```
|
||||
void onInstanceDisposed(String name, Type type, Object instance, {String? scopeName});
|
||||
|
||||
// === Module events ===
|
||||
/// Called when modules are installed into the container.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onModulesInstalled(['NetworkModule', 'RepositoryModule'], scopeName: 'root');
|
||||
/// ```
|
||||
void onModulesInstalled(List<String> moduleNames, {String? scopeName});
|
||||
|
||||
/// Called when modules are removed from the container.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onModulesRemoved(['RepositoryModule'], scopeName: 'root');
|
||||
/// ```
|
||||
void onModulesRemoved(List<String> moduleNames, {String? scopeName});
|
||||
|
||||
// === Scope lifecycle ===
|
||||
/// Called when a new DI scope is opened (for example, starting a new feature or screen).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onScopeOpened('user-session');
|
||||
/// ```
|
||||
void onScopeOpened(String name);
|
||||
|
||||
/// Called when an existing DI scope is closed.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onScopeClosed('user-session');
|
||||
/// ```
|
||||
void onScopeClosed(String name);
|
||||
|
||||
// === Cycle detection ===
|
||||
/// Called if a dependency cycle is detected during resolution.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onCycleDetected(['A', 'B', 'C', 'A'], scopeName: 'root');
|
||||
/// ```
|
||||
void onCycleDetected(List<String> chain, {String? scopeName});
|
||||
|
||||
// === Cache events ===
|
||||
/// Called when an instance is found in the cache.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onCacheHit('MyService', MyService, scopeName: 'root');
|
||||
/// ```
|
||||
void onCacheHit(String name, Type type, {String? scopeName});
|
||||
|
||||
/// Called when an instance is not found in the cache and should be created.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onCacheMiss('MyService', MyService, scopeName: 'root');
|
||||
/// ```
|
||||
void onCacheMiss(String name, Type type, {String? scopeName});
|
||||
|
||||
// === Diagnostic ===
|
||||
/// Used for custom diagnostic and debug messages.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onDiagnostic('Cache cleared', details: detailsObj);
|
||||
/// ```
|
||||
void onDiagnostic(String message, {Object? details});
|
||||
|
||||
// === Warnings & errors ===
|
||||
/// Called on non-fatal, recoverable DI container warnings.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onWarning('Binding override', details: {...});
|
||||
/// ```
|
||||
void onWarning(String message, {Object? details});
|
||||
|
||||
/// Called on error (typically exceptions thrown during resolution, instantiation, or disposal).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onError('Failed to resolve dependency', errorObj, stackTraceObj);
|
||||
/// ```
|
||||
void onError(String message, Object? error, StackTrace? stackTrace);
|
||||
}
|
||||
|
||||
/// Diagnostic/Debug observer that prints all events
|
||||
class PrintCherryPickObserver implements CherryPickObserver {
|
||||
@override
|
||||
void onBindingRegistered(String name, Type type, {String? scopeName}) =>
|
||||
print('[binding][CherryPick] $name — $type (scope: $scopeName)');
|
||||
|
||||
@override
|
||||
void onInstanceRequested(String name, Type type, {String? scopeName}) =>
|
||||
print('[request][CherryPick] $name — $type (scope: $scopeName)');
|
||||
|
||||
@override
|
||||
void onInstanceCreated(String name, Type type, Object instance, {String? scopeName}) =>
|
||||
print('[create][CherryPick] $name — $type => $instance (scope: $scopeName)');
|
||||
|
||||
@override
|
||||
void onInstanceDisposed(String name, Type type, Object instance, {String? scopeName}) =>
|
||||
print('[dispose][CherryPick] $name — $type => $instance (scope: $scopeName)');
|
||||
|
||||
@override
|
||||
void onModulesInstalled(List<String> modules, {String? scopeName}) =>
|
||||
print('[modules installed][CherryPick] ${modules.join(', ')} (scope: $scopeName)');
|
||||
@override
|
||||
void onModulesRemoved(List<String> modules, {String? scopeName}) =>
|
||||
print('[modules removed][CherryPick] ${modules.join(', ')} (scope: $scopeName)');
|
||||
|
||||
@override
|
||||
void onScopeOpened(String name) => print('[scope opened][CherryPick] $name');
|
||||
|
||||
@override
|
||||
void onScopeClosed(String name) => print('[scope closed][CherryPick] $name');
|
||||
|
||||
@override
|
||||
void onCycleDetected(List<String> chain, {String? scopeName}) =>
|
||||
print('[cycle][CherryPick] Detected: ${chain.join(' -> ')}${scopeName != null ? ' (scope: $scopeName)' : ''}');
|
||||
|
||||
@override
|
||||
void onCacheHit(String name, Type type, {String? scopeName}) =>
|
||||
print('[cache hit][CherryPick] $name — $type (scope: $scopeName)');
|
||||
@override
|
||||
void onCacheMiss(String name, Type type, {String? scopeName}) =>
|
||||
print('[cache miss][CherryPick] $name — $type (scope: $scopeName)');
|
||||
|
||||
@override
|
||||
void onDiagnostic(String message, {Object? details}) =>
|
||||
print('[diagnostic][CherryPick] $message ${details ?? ''}');
|
||||
|
||||
@override
|
||||
void onWarning(String message, {Object? details}) =>
|
||||
print('[warn][CherryPick] $message ${details ?? ''}');
|
||||
@override
|
||||
void onError(String message, Object? error, StackTrace? stackTrace) {
|
||||
print('[error][CherryPick] $message');
|
||||
if (error != null) print(' error: $error');
|
||||
if (stackTrace != null) print(' stack: $stackTrace');
|
||||
}
|
||||
}
|
||||
|
||||
/// Silent observer: ignores all events
|
||||
class SilentCherryPickObserver implements CherryPickObserver {
|
||||
@override
|
||||
void onBindingRegistered(String name, Type type, {String? scopeName}) {}
|
||||
@override
|
||||
void onInstanceRequested(String name, Type type, {String? scopeName}) {}
|
||||
@override
|
||||
void onInstanceCreated(String name, Type type, Object instance, {String? scopeName}) {}
|
||||
@override
|
||||
void onInstanceDisposed(String name, Type type, Object instance, {String? scopeName}) {}
|
||||
@override
|
||||
void onModulesInstalled(List<String> modules, {String? scopeName}) {}
|
||||
@override
|
||||
void onModulesRemoved(List<String> modules, {String? scopeName}) {}
|
||||
@override
|
||||
void onScopeOpened(String name) {}
|
||||
@override
|
||||
void onScopeClosed(String name) {}
|
||||
@override
|
||||
void onCycleDetected(List<String> chain, {String? scopeName}) {}
|
||||
@override
|
||||
void onCacheHit(String name, Type type, {String? scopeName}) {}
|
||||
@override
|
||||
void onCacheMiss(String name, Type type, {String? scopeName}) {}
|
||||
@override
|
||||
void onDiagnostic(String message, {Object? details}) {}
|
||||
@override
|
||||
void onWarning(String message, {Object? details}) {}
|
||||
@override
|
||||
void onError(String message, Object? error, StackTrace? stackTrace) {}
|
||||
}
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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,25 +13,16 @@
|
||||
import 'dart:collection';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:cherrypick/src/binding.dart';
|
||||
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';
|
||||
import 'package:cherrypick/src/observer.dart';
|
||||
// import 'package:cherrypick/src/log_format.dart';
|
||||
|
||||
Scope openRootScope() => Scope(null);
|
||||
|
||||
class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
final Scope? _parentScope;
|
||||
|
||||
late final CherryPickObserver _observer;
|
||||
|
||||
@override
|
||||
CherryPickObserver get observer => _observer;
|
||||
|
||||
/// COLLECTS all resolved instances that implement [Disposable].
|
||||
final Set<Disposable> _disposables = HashSet();
|
||||
|
||||
/// RU: Метод возвращает родительский [Scope].
|
||||
///
|
||||
/// ENG: The method returns the parent [Scope].
|
||||
@@ -41,26 +32,13 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
|
||||
final Map<String, Scope> _scopeMap = HashMap();
|
||||
|
||||
Scope(this._parentScope, {required CherryPickObserver observer}) : _observer = observer {
|
||||
Scope(this._parentScope) {
|
||||
// Генерируем уникальный ID для скоупа
|
||||
setScopeId(_generateScopeId());
|
||||
observer.onScopeOpened(scopeId ?? 'NO_ID');
|
||||
observer.onDiagnostic(
|
||||
'Scope created: ${scopeId ?? 'NO_ID'}',
|
||||
details: {
|
||||
'type': 'Scope',
|
||||
'name': scopeId ?? 'NO_ID',
|
||||
if (_parentScope?.scopeId != null) 'parent': _parentScope!.scopeId,
|
||||
'description': 'scope created',
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
final Set<Module> _modulesList = HashSet();
|
||||
|
||||
// индекс для мгновенного поиска binding’ов
|
||||
final Map<Object, Map<String?, BindingResolver>> _bindingResolvers = {};
|
||||
|
||||
|
||||
/// RU: Генерирует уникальный идентификатор для скоупа.
|
||||
/// ENG: Generates unique identifier for scope.
|
||||
String _generateScopeId() {
|
||||
@@ -77,8 +55,8 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
/// return [Scope]
|
||||
Scope openSubScope(String name) {
|
||||
if (!_scopeMap.containsKey(name)) {
|
||||
final childScope = Scope(this, observer: observer); // Наследуем observer вниз по иерархии
|
||||
// print removed (trace)
|
||||
final childScope = Scope(this);
|
||||
|
||||
// Наследуем настройки обнаружения циклических зависимостей
|
||||
if (isCycleDetectionEnabled) {
|
||||
childScope.enableCycleDetection();
|
||||
@@ -86,45 +64,24 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
childScope.enableGlobalCycleDetection();
|
||||
}
|
||||
|
||||
_scopeMap[name] = childScope;
|
||||
observer.onDiagnostic(
|
||||
'SubScope created: $name',
|
||||
details: {
|
||||
'type': 'SubScope',
|
||||
'name': name,
|
||||
'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] asynchronously.
|
||||
/// ENG: The method closes child (additional) [Scope].
|
||||
///
|
||||
/// return [Future<void>]
|
||||
Future<void> closeSubScope(String name) async {
|
||||
/// return [Scope]
|
||||
void closeSubScope(String name) {
|
||||
final childScope = _scopeMap[name];
|
||||
if (childScope != null) {
|
||||
await childScope.dispose(); // асинхронный вызов
|
||||
// Очищаем детектор для дочернего скоупа
|
||||
if (childScope.scopeId != null) {
|
||||
GlobalCycleDetector.instance.removeScopeDetector(childScope.scopeId!);
|
||||
}
|
||||
observer.onScopeClosed(childScope.scopeId ?? name);
|
||||
observer.onDiagnostic(
|
||||
'SubScope closed: $name',
|
||||
details: {
|
||||
'type': 'SubScope',
|
||||
'name': name,
|
||||
'id': childScope.scopeId,
|
||||
if (scopeId != null) 'parent': scopeId,
|
||||
'description': 'subscope closed',
|
||||
},
|
||||
);
|
||||
}
|
||||
_scopeMap.remove(name);
|
||||
}
|
||||
@@ -136,30 +93,9 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
/// return [Scope]
|
||||
Scope installModules(List<Module> modules) {
|
||||
_modulesList.addAll(modules);
|
||||
if (modules.isNotEmpty) {
|
||||
observer.onModulesInstalled(
|
||||
modules.map((m) => m.runtimeType.toString()).toList(),
|
||||
scopeName: scopeId,
|
||||
);
|
||||
}
|
||||
for (var module in modules) {
|
||||
observer.onDiagnostic(
|
||||
'Module installed: ${module.runtimeType}',
|
||||
details: {
|
||||
'type': 'Module',
|
||||
'name': module.runtimeType.toString(),
|
||||
'scope': scopeId,
|
||||
'description': 'module installed',
|
||||
},
|
||||
);
|
||||
module.builder(this);
|
||||
// После builder: для всех новых биндингов
|
||||
for (final binding in module.bindingSet) {
|
||||
binding.observer = observer;
|
||||
binding.logAllDeferred();
|
||||
}
|
||||
}
|
||||
_rebuildResolversIndex();
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -169,22 +105,9 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
///
|
||||
/// return [Scope]
|
||||
Scope dropModules() {
|
||||
if (_modulesList.isNotEmpty) {
|
||||
observer.onModulesRemoved(
|
||||
_modulesList.map((m) => m.runtimeType.toString()).toList(),
|
||||
scopeName: scopeId,
|
||||
);
|
||||
}
|
||||
observer.onDiagnostic(
|
||||
'Modules dropped for scope: $scopeId',
|
||||
details: {
|
||||
'type': 'Scope',
|
||||
'name': scopeId,
|
||||
'description': 'modules dropped',
|
||||
},
|
||||
);
|
||||
// [AlexeyYuPopkov](https://github.com/AlexeyYuPopkov) Thank you for the [Removed exception "ConcurrentModificationError"](https://github.com/pese-git/cherrypick/pull/2)
|
||||
_modulesList.clear();
|
||||
_rebuildResolversIndex();
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -200,36 +123,14 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
/// return - returns an object of type [T] or [StateError]
|
||||
///
|
||||
T resolve<T>({String? named, dynamic params}) {
|
||||
observer.onInstanceRequested(T.toString(), T, scopeName: scopeId);
|
||||
// Используем глобальное отслеживание, если включено
|
||||
T result;
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
try {
|
||||
result = withGlobalCycleDetection<T>(T, named, () {
|
||||
return _resolveWithLocalDetection<T>(named: named, params: params);
|
||||
});
|
||||
} catch (e, s) {
|
||||
observer.onError(
|
||||
'Global cycle detection failed during resolve: $T',
|
||||
e,
|
||||
s,
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
return withGlobalCycleDetection<T>(T, named, () {
|
||||
return _resolveWithLocalDetection<T>(named: named, params: params);
|
||||
});
|
||||
} else {
|
||||
try {
|
||||
result = _resolveWithLocalDetection<T>(named: named, params: params);
|
||||
} catch (e, s) {
|
||||
observer.onError(
|
||||
'Failed to resolve: $T',
|
||||
e,
|
||||
s,
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
return _resolveWithLocalDetection<T>(named: named, params: params);
|
||||
}
|
||||
_trackDisposable(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// RU: Разрешение с локальным детектором циклических зависимостей.
|
||||
@@ -238,24 +139,8 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
return withCycleDetection<T>(T, named, () {
|
||||
var resolved = _tryResolveInternal<T>(named: named, params: params);
|
||||
if (resolved != null) {
|
||||
observer.onInstanceCreated(T.toString(), T, resolved, scopeName: scopeId);
|
||||
observer.onDiagnostic(
|
||||
'Successfully resolved: $T',
|
||||
details: {
|
||||
'type': 'Scope',
|
||||
'name': scopeId,
|
||||
'resolve': T.toString(),
|
||||
if (named != null) 'named': named,
|
||||
'description': 'successfully resolved',
|
||||
},
|
||||
);
|
||||
return resolved;
|
||||
} else {
|
||||
observer.onError(
|
||||
'Failed to resolve: $T',
|
||||
null,
|
||||
null,
|
||||
);
|
||||
throw StateError(
|
||||
'Can\'t resolve dependency `$T`. Maybe you forget register it?');
|
||||
}
|
||||
@@ -267,16 +152,13 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
///
|
||||
T? tryResolve<T>({String? named, dynamic params}) {
|
||||
// Используем глобальное отслеживание, если включено
|
||||
T? result;
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
result = withGlobalCycleDetection<T?>(T, named, () {
|
||||
return withGlobalCycleDetection<T?>(T, named, () {
|
||||
return _tryResolveWithLocalDetection<T>(named: named, params: params);
|
||||
});
|
||||
} else {
|
||||
result = _tryResolveWithLocalDetection<T>(named: named, params: params);
|
||||
return _tryResolveWithLocalDetection<T>(named: named, params: params);
|
||||
}
|
||||
if (result != null) _trackDisposable(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// RU: Попытка разрешения с локальным детектором циклических зависимостей.
|
||||
@@ -294,12 +176,33 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
/// RU: Внутренний метод для разрешения зависимостей без проверки циклических зависимостей.
|
||||
/// ENG: Internal method for dependency resolution without circular dependency checking.
|
||||
T? _tryResolveInternal<T>({String? named, dynamic params}) {
|
||||
final resolver = _findBindingResolver<T>(named);
|
||||
|
||||
// 1 Поиск зависимости по всем модулям текущего скоупа
|
||||
return resolver?.resolveSync(params) ??
|
||||
// 2 Поиск зависимостей в родительском скоупе
|
||||
_parentScope?.tryResolve(named: named, params: params);
|
||||
if (_modulesList.isNotEmpty) {
|
||||
for (var module in _modulesList) {
|
||||
for (var binding in module.bindingSet) {
|
||||
if (binding.key == T &&
|
||||
((!binding.isNamed && named == null) ||
|
||||
(binding.isNamed && named == binding.name))) {
|
||||
switch (binding.mode) {
|
||||
case Mode.instance:
|
||||
return binding.instance;
|
||||
case Mode.providerInstance:
|
||||
return binding.provider;
|
||||
case Mode.providerInstanceWithParams:
|
||||
if (params == null) {
|
||||
throw StateError('Param is null. Maybe you forget pass it');
|
||||
}
|
||||
return binding.providerWithParams(params);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2 Поиск зависимостей в родительском скоупе
|
||||
return _parentScope?._tryResolveInternal(named: named, params: params);
|
||||
}
|
||||
|
||||
/// RU: Асинхронно возвращает найденную зависимость, определенную параметром типа [T].
|
||||
@@ -314,16 +217,13 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
///
|
||||
Future<T> resolveAsync<T>({String? named, dynamic params}) async {
|
||||
// Используем глобальное отслеживание, если включено
|
||||
T result;
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
result = await withGlobalCycleDetection<Future<T>>(T, named, () async {
|
||||
return withGlobalCycleDetection<Future<T>>(T, named, () async {
|
||||
return await _resolveAsyncWithLocalDetection<T>(named: named, params: params);
|
||||
});
|
||||
} else {
|
||||
result = await _resolveAsyncWithLocalDetection<T>(named: named, params: params);
|
||||
return await _resolveAsyncWithLocalDetection<T>(named: named, params: params);
|
||||
}
|
||||
_trackDisposable(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// RU: Асинхронное разрешение с локальным детектором циклических зависимостей.
|
||||
@@ -332,24 +232,8 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
return withCycleDetection<Future<T>>(T, named, () async {
|
||||
var resolved = await _tryResolveAsyncInternal<T>(named: named, params: params);
|
||||
if (resolved != null) {
|
||||
observer.onInstanceCreated(T.toString(), T, resolved, scopeName: scopeId);
|
||||
observer.onDiagnostic(
|
||||
'Successfully async resolved: $T',
|
||||
details: {
|
||||
'type': 'Scope',
|
||||
'name': scopeId,
|
||||
'resolve': T.toString(),
|
||||
if (named != null) 'named': named,
|
||||
'description': 'successfully resolved (async)',
|
||||
},
|
||||
);
|
||||
return resolved;
|
||||
} else {
|
||||
observer.onError(
|
||||
'Failed to async resolve: $T',
|
||||
null,
|
||||
null,
|
||||
);
|
||||
throw StateError(
|
||||
'Can\'t resolve async dependency `$T`. Maybe you forget register it?');
|
||||
}
|
||||
@@ -358,16 +242,13 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
|
||||
Future<T?> tryResolveAsync<T>({String? named, dynamic params}) async {
|
||||
// Используем глобальное отслеживание, если включено
|
||||
T? result;
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
result = await withGlobalCycleDetection<Future<T?>>(T, named, () async {
|
||||
return withGlobalCycleDetection<Future<T?>>(T, named, () async {
|
||||
return await _tryResolveAsyncWithLocalDetection<T>(named: named, params: params);
|
||||
});
|
||||
} else {
|
||||
result = await _tryResolveAsyncWithLocalDetection<T>(named: named, params: params);
|
||||
return await _tryResolveAsyncWithLocalDetection<T>(named: named, params: params);
|
||||
}
|
||||
if (result != null) _trackDisposable(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// RU: Асинхронная попытка разрешения с локальным детектором циклических зависимостей.
|
||||
@@ -385,49 +266,30 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
/// RU: Внутренний метод для асинхронного разрешения зависимостей без проверки циклических зависимостей.
|
||||
/// ENG: Internal method for async dependency resolution without circular dependency checking.
|
||||
Future<T?> _tryResolveAsyncInternal<T>({String? named, dynamic params}) async {
|
||||
final resolver = _findBindingResolver<T>(named);
|
||||
if (_modulesList.isNotEmpty) {
|
||||
for (var module in _modulesList) {
|
||||
for (var binding in module.bindingSet) {
|
||||
if (binding.key == T &&
|
||||
((!binding.isNamed && named == null) ||
|
||||
(binding.isNamed && named == binding.name))) {
|
||||
if (binding.instanceAsync != null) {
|
||||
return await binding.instanceAsync;
|
||||
}
|
||||
|
||||
// 1 Поиск зависимости по всем модулям текущего скоупа
|
||||
return resolver?.resolveAsync(params) ??
|
||||
// 2 Поиск зависимостей в родительском скоупе
|
||||
_parentScope?.tryResolveAsync(named: named, params: params);
|
||||
}
|
||||
if (binding.asyncProvider != null) {
|
||||
return await binding.asyncProvider?.call();
|
||||
}
|
||||
|
||||
BindingResolver<T>? _findBindingResolver<T>(String? named) =>
|
||||
_bindingResolvers[T]?[named] as BindingResolver<T>?;
|
||||
|
||||
// Индексируем все binding’и после каждого installModules/dropModules
|
||||
void _rebuildResolversIndex() {
|
||||
_bindingResolvers.clear();
|
||||
for (var module in _modulesList) {
|
||||
for (var binding in module.bindingSet) {
|
||||
_bindingResolvers.putIfAbsent(binding.key, () => {});
|
||||
final nameKey = binding.isNamed ? binding.name : null;
|
||||
_bindingResolvers[binding.key]![nameKey] = binding.resolver!;
|
||||
if (binding.asyncProviderWithParams != null) {
|
||||
if (params == null) {
|
||||
throw StateError('Param is null. Maybe you forget pass it');
|
||||
}
|
||||
return await binding.asyncProviderWithParams!(params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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();
|
||||
return _parentScope?._tryResolveAsyncInternal(named: named, params: params);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,10 @@
|
||||
name: cherrypick
|
||||
description: Cherrypick is a small dependency injection (DI) library for dart/flutter projects.
|
||||
version: 3.0.0-dev.8
|
||||
version: 3.0.0-dev.0
|
||||
homepage: https://pese-git.github.io/cherrypick-site/
|
||||
documentation: https://github.com/pese-git/cherrypick/wiki
|
||||
repository: https://github.com/pese-git/cherrypick
|
||||
issue_tracker: https://github.com/pese-git/cherrypick/issues
|
||||
topics:
|
||||
- di
|
||||
- ioc
|
||||
- dependency-injection
|
||||
- dependency-management
|
||||
- inversion-of-control
|
||||
|
||||
environment:
|
||||
sdk: ">=3.5.2 <4.0.0"
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
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 MockObserver observer;
|
||||
|
||||
setUp(() {
|
||||
observer = MockObserver();
|
||||
});
|
||||
|
||||
test('Global logger receives Binding events', () {
|
||||
final scope = Scope(null, observer: observer);
|
||||
scope.installModules([DummyModule()]);
|
||||
final _ = scope.resolve<DummyService>(named: 'test');
|
||||
|
||||
// Проверяем, что биндинг DummyService зарегистрирован
|
||||
expect(
|
||||
observer.bindings.any((m) => m.contains('DummyService')),
|
||||
isTrue,
|
||||
);
|
||||
// Можно добавить проверки diagnostics, если Scope что-то пишет туда
|
||||
});
|
||||
|
||||
test('CycleDetector logs cycle detection error', () {
|
||||
final scope = Scope(null, observer: observer);
|
||||
// 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>()),
|
||||
);
|
||||
// Проверяем, что цикл зафиксирован либо в errors, либо в diagnostics либо cycles
|
||||
final foundInErrors = observer.errors.any((m) => m.contains('cycle detected'));
|
||||
final foundInDiagnostics = observer.diagnostics.any((m) => m.contains('cycle detected'));
|
||||
final foundCycleNotified = observer.cycles.isNotEmpty;
|
||||
expect(foundInErrors || foundInDiagnostics || foundCycleNotified, isTrue,
|
||||
reason: 'Ожидаем хотя бы один лог о цикле! errors: ${observer.errors}\ndiag: ${observer.diagnostics}\ncycles: ${observer.cycles}');
|
||||
});
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
class MockObserver implements CherryPickObserver {
|
||||
final List<String> diagnostics = [];
|
||||
final List<String> warnings = [];
|
||||
final List<String> errors = [];
|
||||
final List<List<String>> cycles = [];
|
||||
final List<String> bindings = [];
|
||||
|
||||
@override
|
||||
void onDiagnostic(String message, {Object? details}) =>
|
||||
diagnostics.add(message);
|
||||
|
||||
@override
|
||||
void onWarning(String message, {Object? details}) => warnings.add(message);
|
||||
|
||||
@override
|
||||
void onError(String message, Object? error, StackTrace? stackTrace) =>
|
||||
errors.add(
|
||||
'$message${error != null ? ' $error' : ''}${stackTrace != null ? '\n$stackTrace' : ''}');
|
||||
|
||||
@override
|
||||
void onCycleDetected(List<String> chain, {String? scopeName}) =>
|
||||
cycles.add(chain);
|
||||
|
||||
@override
|
||||
void onBindingRegistered(String name, Type type, {String? scopeName}) =>
|
||||
bindings.add('$name $type');
|
||||
|
||||
@override
|
||||
void onInstanceRequested(String name, Type type, {String? scopeName}) {}
|
||||
@override
|
||||
void onInstanceCreated(String name, Type type, Object instance, {String? scopeName}) {}
|
||||
@override
|
||||
void onInstanceDisposed(String name, Type type, Object instance, {String? scopeName}) {}
|
||||
@override
|
||||
void onModulesInstalled(List<String> moduleNames, {String? scopeName}) {}
|
||||
@override
|
||||
void onModulesRemoved(List<String> moduleNames, {String? scopeName}) {}
|
||||
@override
|
||||
void onScopeOpened(String name) {}
|
||||
@override
|
||||
void onScopeClosed(String name) {}
|
||||
@override
|
||||
void onCacheHit(String name, Type type, {String? scopeName}) {}
|
||||
@override
|
||||
void onCacheMiss(String name, Type type, {String? scopeName}) {}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:cherrypick/src/binding.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
@@ -7,12 +7,12 @@ void main() {
|
||||
group('Without name', () {
|
||||
test('Returns null by default', () {
|
||||
final binding = Binding<int>();
|
||||
expect(binding.resolver, null);
|
||||
expect(binding.instance, null);
|
||||
});
|
||||
|
||||
test('Sets mode to instance', () {
|
||||
final binding = Binding<int>().toInstance(5);
|
||||
expect(binding.resolver, isA<InstanceResolver<int>>());
|
||||
expect(binding.mode, Mode.instance);
|
||||
});
|
||||
|
||||
test('isSingleton is true', () {
|
||||
@@ -22,19 +22,19 @@ void main() {
|
||||
|
||||
test('Stores value', () {
|
||||
final binding = Binding<int>().toInstance(5);
|
||||
expect(binding.resolver?.resolveSync(), 5);
|
||||
expect(binding.instance, 5);
|
||||
});
|
||||
});
|
||||
|
||||
group('With name', () {
|
||||
test('Returns null by default', () {
|
||||
final binding = Binding<int>().withName('n');
|
||||
expect(binding.resolver, null);
|
||||
expect(binding.instance, null);
|
||||
});
|
||||
|
||||
test('Sets mode to instance', () {
|
||||
final binding = Binding<int>().withName('n').toInstance(5);
|
||||
expect(binding.resolver, isA<InstanceResolver<int>>());
|
||||
expect(binding.mode, Mode.instance);
|
||||
});
|
||||
|
||||
test('Sets key', () {
|
||||
@@ -49,7 +49,7 @@ void main() {
|
||||
|
||||
test('Stores value', () {
|
||||
final binding = Binding<int>().withName('n').toInstance(5);
|
||||
expect(binding.resolver?.resolveSync(), 5);
|
||||
expect(binding.instance, 5);
|
||||
});
|
||||
|
||||
test('Sets name', () {
|
||||
@@ -60,39 +60,45 @@ void main() {
|
||||
|
||||
test('Multiple toInstance calls change value', () {
|
||||
final binding = Binding<int>().toInstance(1).toInstance(2);
|
||||
expect(binding.resolver?.resolveSync(), 2);
|
||||
expect(binding.instance, 2);
|
||||
});
|
||||
});
|
||||
|
||||
// --- Instance binding (asynchronous) ---
|
||||
group('Async Instance Binding (toInstanceAsync)', () {
|
||||
test('Resolves instanceAsync with expected value', () async {
|
||||
final binding = Binding<int>().toInstance(Future.value(42));
|
||||
expect(await binding.resolveAsync(), 42);
|
||||
final binding = Binding<int>().toInstanceAsync(Future.value(42));
|
||||
expect(await binding.instanceAsync, 42);
|
||||
});
|
||||
|
||||
test('Does not affect instance', () {
|
||||
final binding = Binding<int>().toInstanceAsync(Future.value(5));
|
||||
expect(binding.instance, null);
|
||||
});
|
||||
|
||||
test('Sets mode to instance', () {
|
||||
final binding = Binding<int>().toInstance(Future.value(5));
|
||||
expect(binding.resolver, isA<InstanceResolver<int>>());
|
||||
final binding = Binding<int>().toInstanceAsync(Future.value(5));
|
||||
expect(binding.mode, Mode.instance);
|
||||
});
|
||||
|
||||
test('isSingleton is true after toInstanceAsync', () {
|
||||
final binding = Binding<int>().toInstance(Future.value(5));
|
||||
final binding = Binding<int>().toInstanceAsync(Future.value(5));
|
||||
expect(binding.isSingleton, isTrue);
|
||||
});
|
||||
|
||||
test('Composes with withName', () async {
|
||||
final binding =
|
||||
Binding<int>().withName('asyncValue').toInstance(Future.value(7));
|
||||
final binding = Binding<int>()
|
||||
.withName('asyncValue')
|
||||
.toInstanceAsync(Future.value(7));
|
||||
expect(binding.isNamed, isTrue);
|
||||
expect(binding.name, 'asyncValue');
|
||||
expect(await binding.resolveAsync(), 7);
|
||||
expect(await binding.instanceAsync, 7);
|
||||
});
|
||||
|
||||
test('Keeps value after multiple awaits', () async {
|
||||
final binding = Binding<int>().toInstance(Future.value(123));
|
||||
final result1 = await binding.resolveAsync();
|
||||
final result2 = await binding.resolveAsync();
|
||||
final binding = Binding<int>().toInstanceAsync(Future.value(123));
|
||||
final result1 = await binding.instanceAsync;
|
||||
final result2 = await binding.instanceAsync;
|
||||
expect(result1, equals(result2));
|
||||
});
|
||||
});
|
||||
@@ -102,12 +108,12 @@ void main() {
|
||||
group('Without name', () {
|
||||
test('Returns null by default', () {
|
||||
final binding = Binding<int>();
|
||||
expect(binding.resolver, null);
|
||||
expect(binding.provider, null);
|
||||
});
|
||||
|
||||
test('Sets mode to providerInstance', () {
|
||||
final binding = Binding<int>().toProvide(() => 5);
|
||||
expect(binding.resolver, isA<ProviderResolver<int>>());
|
||||
expect(binding.mode, Mode.providerInstance);
|
||||
});
|
||||
|
||||
test('isSingleton is false by default', () {
|
||||
@@ -117,19 +123,19 @@ void main() {
|
||||
|
||||
test('Returns provided value', () {
|
||||
final binding = Binding<int>().toProvide(() => 5);
|
||||
expect(binding.resolveSync(), 5);
|
||||
expect(binding.provider, 5);
|
||||
});
|
||||
});
|
||||
|
||||
group('With name', () {
|
||||
test('Returns null by default', () {
|
||||
final binding = Binding<int>().withName('n');
|
||||
expect(binding.resolver, null);
|
||||
expect(binding.provider, null);
|
||||
});
|
||||
|
||||
test('Sets mode to providerInstance', () {
|
||||
final binding = Binding<int>().withName('n').toProvide(() => 5);
|
||||
expect(binding.resolver, isA<ProviderResolver<int>>());
|
||||
expect(binding.mode, Mode.providerInstance);
|
||||
});
|
||||
|
||||
test('Sets key', () {
|
||||
@@ -144,7 +150,7 @@ void main() {
|
||||
|
||||
test('Returns provided value', () {
|
||||
final binding = Binding<int>().withName('n').toProvide(() => 5);
|
||||
expect(binding.resolveSync(), 5);
|
||||
expect(binding.provider, 5);
|
||||
});
|
||||
|
||||
test('Sets name', () {
|
||||
@@ -157,14 +163,14 @@ void main() {
|
||||
// --- Async provider binding ---
|
||||
group('Async Provider Binding', () {
|
||||
test('Resolves asyncProvider value', () async {
|
||||
final binding = Binding<int>().toProvide(() async => 5);
|
||||
expect(await binding.resolveAsync(), 5);
|
||||
final binding = Binding<int>().toProvideAsync(() async => 5);
|
||||
expect(await binding.asyncProvider?.call(), 5);
|
||||
});
|
||||
|
||||
test('Resolves asyncProviderWithParams value', () async {
|
||||
final binding = Binding<int>()
|
||||
.toProvideWithParams((param) async => 5 + (param as int));
|
||||
expect(await binding.resolveAsync(3), 8);
|
||||
.toProvideAsyncWithParams((param) async => 5 + (param as int));
|
||||
expect(await binding.asyncProviderWithParams?.call(3), 8);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -173,7 +179,12 @@ void main() {
|
||||
group('Without name', () {
|
||||
test('Returns null if no provider set', () {
|
||||
final binding = Binding<int>().singleton();
|
||||
expect(binding.resolver, null);
|
||||
expect(binding.provider, null);
|
||||
});
|
||||
|
||||
test('Sets mode to providerInstance', () {
|
||||
final binding = Binding<int>().toProvide(() => 5).singleton();
|
||||
expect(binding.mode, Mode.providerInstance);
|
||||
});
|
||||
|
||||
test('isSingleton is true', () {
|
||||
@@ -183,7 +194,7 @@ void main() {
|
||||
|
||||
test('Returns singleton value', () {
|
||||
final binding = Binding<int>().toProvide(() => 5).singleton();
|
||||
expect(binding.resolveSync(), 5);
|
||||
expect(binding.provider, 5);
|
||||
});
|
||||
|
||||
test('Returns same value each call and provider only called once', () {
|
||||
@@ -193,8 +204,8 @@ void main() {
|
||||
return counter;
|
||||
}).singleton();
|
||||
|
||||
final first = binding.resolveSync();
|
||||
final second = binding.resolveSync();
|
||||
final first = binding.provider;
|
||||
final second = binding.provider;
|
||||
expect(first, equals(second));
|
||||
expect(counter, 1);
|
||||
});
|
||||
@@ -203,7 +214,13 @@ void main() {
|
||||
group('With name', () {
|
||||
test('Returns null if no provider set', () {
|
||||
final binding = Binding<int>().withName('n').singleton();
|
||||
expect(binding.resolver, null);
|
||||
expect(binding.provider, null);
|
||||
});
|
||||
|
||||
test('Sets mode to providerInstance', () {
|
||||
final binding =
|
||||
Binding<int>().withName('n').toProvide(() => 5).singleton();
|
||||
expect(binding.mode, Mode.providerInstance);
|
||||
});
|
||||
|
||||
test('Sets key', () {
|
||||
@@ -221,7 +238,7 @@ void main() {
|
||||
test('Returns singleton value', () {
|
||||
final binding =
|
||||
Binding<int>().withName('n').toProvide(() => 5).singleton();
|
||||
expect(binding.resolveSync(), 5);
|
||||
expect(binding.provider, 5);
|
||||
});
|
||||
|
||||
test('Sets name', () {
|
||||
@@ -230,6 +247,12 @@ void main() {
|
||||
expect(binding.name, 'n');
|
||||
});
|
||||
});
|
||||
|
||||
test('Chained withName and singleton preserves mode', () {
|
||||
final binding =
|
||||
Binding<int>().toProvide(() => 3).withName("named").singleton();
|
||||
expect(binding.mode, Mode.providerInstance);
|
||||
});
|
||||
});
|
||||
|
||||
// --- WithName / Named binding, isNamed, edge-cases ---
|
||||
@@ -242,7 +265,7 @@ void main() {
|
||||
|
||||
test('providerWithParams returns null if not set', () {
|
||||
final binding = Binding<int>();
|
||||
expect(binding.resolveSync(123), null);
|
||||
expect(binding.providerWithParams(123), null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,19 +1,14 @@
|
||||
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 MockObserver observer;
|
||||
setUp(() {
|
||||
observer = MockObserver();
|
||||
CherryPick.setGlobalObserver(observer);
|
||||
});
|
||||
group('CycleDetector', () {
|
||||
late CycleDetector detector;
|
||||
|
||||
setUp(() {
|
||||
detector = CycleDetector(observer: observer);
|
||||
detector = CycleDetector();
|
||||
});
|
||||
|
||||
test('should detect simple circular dependency', () {
|
||||
@@ -80,7 +75,7 @@ void main() {
|
||||
|
||||
group('Scope with Cycle Detection', () {
|
||||
test('should detect circular dependency in real scenario', () {
|
||||
final scope = CherryPick.openRootScope();
|
||||
final scope = Scope(null);
|
||||
scope.enableCycleDetection();
|
||||
|
||||
// Создаем циклическую зависимость: A зависит от B, B зависит от A
|
||||
@@ -96,7 +91,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('should work normally without cycle detection enabled', () {
|
||||
final scope = CherryPick.openRootScope();
|
||||
final scope = Scope(null);
|
||||
// Не включаем обнаружение циклических зависимостей
|
||||
|
||||
scope.installModules([
|
||||
@@ -108,7 +103,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('should allow disabling cycle detection', () {
|
||||
final scope = CherryPick.openRootScope();
|
||||
final scope = Scope(null);
|
||||
scope.enableCycleDetection();
|
||||
expect(scope.isCycleDetectionEnabled, isTrue);
|
||||
|
||||
@@ -117,7 +112,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('should handle named dependencies in cycle detection', () {
|
||||
final scope = CherryPick.openRootScope();
|
||||
final scope = Scope(null);
|
||||
scope.enableCycleDetection();
|
||||
|
||||
scope.installModules([
|
||||
@@ -131,7 +126,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('should detect cycles in async resolution', () async {
|
||||
final scope = CherryPick.openRootScope();
|
||||
final scope = Scope(null);
|
||||
scope.enableCycleDetection();
|
||||
|
||||
scope.installModules([
|
||||
@@ -205,13 +200,11 @@ class AsyncServiceB {
|
||||
class AsyncCircularModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
// ignore: deprecated_member_use_from_same_package
|
||||
bind<AsyncServiceA>().toProvideAsync(() async {
|
||||
final serviceB = await currentScope.resolveAsync<AsyncServiceB>();
|
||||
return AsyncServiceA(serviceB);
|
||||
});
|
||||
|
||||
// ignore: deprecated_member_use_from_same_package
|
||||
bind<AsyncServiceB>().toProvideAsync(() async {
|
||||
final serviceA = await currentScope.resolveAsync<AsyncServiceA>();
|
||||
return AsyncServiceB(serviceA);
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:test/test.dart';
|
||||
import '../mock_logger.dart';
|
||||
|
||||
void main() {
|
||||
late MockObserver observer;
|
||||
setUp(() {
|
||||
observer = MockObserver();
|
||||
CherryPick.setGlobalObserver(observer);
|
||||
});
|
||||
group('CherryPick Cycle Detection Helper Methods', () {
|
||||
setUp(() {
|
||||
// Сбрасываем состояние перед каждым тестом
|
||||
|
||||
@@ -1,187 +1,76 @@
|
||||
import 'package:cherrypick/cherrypick.dart' show Disposable, Module, Scope, CherryPick;
|
||||
import 'dart:async';
|
||||
import 'package:cherrypick/src/module.dart';
|
||||
import 'package:cherrypick/src/scope.dart';
|
||||
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 observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer);
|
||||
final scope = Scope(null);
|
||||
expect(scope.parentScope, null);
|
||||
});
|
||||
|
||||
test('Can open and retrieve the same subScope by key', () {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer);
|
||||
expect(Scope(scope, observer: observer), isNotNull); // эквивалент
|
||||
});
|
||||
test('closeSubScope removes subscope so next openSubScope returns new', () async {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer);
|
||||
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)));
|
||||
final scope = Scope(null);
|
||||
final subScope = scope.openSubScope('subScope');
|
||||
expect(scope.openSubScope('subScope'), subScope);
|
||||
});
|
||||
|
||||
test('closeSubScope removes subscope so next openSubScope returns new', () {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer);
|
||||
expect(Scope(scope, observer: observer), isNotNull); // эквивалент
|
||||
// Нет необходимости тестировать open/closeSubScope в этом юните
|
||||
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)));
|
||||
});
|
||||
});
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
group('Dependency Resolution (standard)', () {
|
||||
test("Throws StateError if value can't be resolved", () {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer);
|
||||
final scope = Scope(null);
|
||||
expect(() => scope.resolve<String>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
|
||||
test('Resolves value after adding a dependency', () {
|
||||
final observer = MockObserver();
|
||||
final expectedValue = 'test string';
|
||||
final scope = Scope(null, observer: observer)
|
||||
final scope = Scope(null)
|
||||
.installModules([TestModule<String>(value: expectedValue)]);
|
||||
expect(scope.resolve<String>(), expectedValue);
|
||||
});
|
||||
|
||||
test('Returns a value from parent scope', () {
|
||||
final observer = MockObserver();
|
||||
final expectedValue = 5;
|
||||
final parentScope = Scope(null, observer: observer);
|
||||
final scope = Scope(parentScope, observer: observer);
|
||||
final parentScope = Scope(null);
|
||||
final scope = Scope(parentScope);
|
||||
|
||||
parentScope.installModules([TestModule<int>(value: expectedValue)]);
|
||||
|
||||
expect(scope.resolve<int>(), expectedValue);
|
||||
});
|
||||
|
||||
test('Returns several values from parent container', () {
|
||||
final observer = MockObserver();
|
||||
final expectedIntValue = 5;
|
||||
final expectedStringValue = 'Hello world';
|
||||
final parentScope = Scope(null, observer: observer).installModules([
|
||||
final parentScope = Scope(null).installModules([
|
||||
TestModule<int>(value: expectedIntValue),
|
||||
TestModule<String>(value: expectedStringValue)
|
||||
]);
|
||||
final scope = Scope(parentScope, observer: observer);
|
||||
final scope = Scope(parentScope);
|
||||
|
||||
expect(scope.resolve<int>(), expectedIntValue);
|
||||
expect(scope.resolve<String>(), expectedStringValue);
|
||||
});
|
||||
|
||||
test("Throws StateError if parent hasn't value too", () {
|
||||
final observer = MockObserver();
|
||||
final parentScope = Scope(null, observer: observer);
|
||||
final scope = Scope(parentScope, observer: observer);
|
||||
final parentScope = Scope(null);
|
||||
final scope = Scope(parentScope);
|
||||
expect(() => scope.resolve<int>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
|
||||
test("After dropModules resolves fail", () {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer)..installModules([TestModule<int>(value: 5)]);
|
||||
final scope = Scope(null)..installModules([TestModule<int>(value: 5)]);
|
||||
expect(scope.resolve<int>(), 5);
|
||||
scope.dropModules();
|
||||
expect(() => scope.resolve<int>(), throwsA(isA<StateError>()));
|
||||
@@ -191,8 +80,7 @@ void main() {
|
||||
// --------------------------------------------------------------------------
|
||||
group('Named Dependencies', () {
|
||||
test('Resolve named binding', () {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer)
|
||||
final scope = Scope(null)
|
||||
..installModules([
|
||||
TestModule<String>(value: "first"),
|
||||
TestModule<String>(value: "second", name: "special")
|
||||
@@ -200,18 +88,18 @@ void main() {
|
||||
expect(scope.resolve<String>(named: "special"), "second");
|
||||
expect(scope.resolve<String>(), "first");
|
||||
});
|
||||
|
||||
test('Named binding does not clash with unnamed', () {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer)
|
||||
final scope = Scope(null)
|
||||
..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 observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer)
|
||||
final scope = Scope(null)
|
||||
..installModules([
|
||||
TestModule<String>(value: "foo"),
|
||||
]);
|
||||
@@ -222,8 +110,7 @@ void main() {
|
||||
// --------------------------------------------------------------------------
|
||||
group('Provider with parameters', () {
|
||||
test('Resolve dependency using providerWithParams', () {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer)
|
||||
final scope = Scope(null)
|
||||
..installModules([
|
||||
_InlineModule((m, s) {
|
||||
m.bind<int>().toProvideWithParams((param) => (param as int) * 2);
|
||||
@@ -237,39 +124,38 @@ void main() {
|
||||
// --------------------------------------------------------------------------
|
||||
group('Async Resolution', () {
|
||||
test('Resolve async instance', () async {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer)
|
||||
final scope = Scope(null)
|
||||
..installModules([
|
||||
_InlineModule((m, s) {
|
||||
m.bind<String>().toInstance(Future.value('async value'));
|
||||
m.bind<String>().toInstanceAsync(Future.value('async value'));
|
||||
}),
|
||||
]);
|
||||
expect(await scope.resolveAsync<String>(), "async value");
|
||||
});
|
||||
|
||||
test('Resolve async provider', () async {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer)
|
||||
final scope = Scope(null)
|
||||
..installModules([
|
||||
_InlineModule((m, s) {
|
||||
m.bind<int>().toProvide(() async => 7);
|
||||
m.bind<int>().toProvideAsync(() async => 7);
|
||||
}),
|
||||
]);
|
||||
expect(await scope.resolveAsync<int>(), 7);
|
||||
});
|
||||
|
||||
test('Resolve async provider with param', () async {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer)
|
||||
final scope = Scope(null)
|
||||
..installModules([
|
||||
_InlineModule((m, s) {
|
||||
m.bind<int>().toProvideWithParams((x) async => (x as int) * 3);
|
||||
m.bind<int>().toProvideAsyncWithParams((x) async => (x as int) * 3);
|
||||
}),
|
||||
]);
|
||||
expect(await scope.resolveAsync<int>(params: 2), 6);
|
||||
expect(() => scope.resolveAsync<int>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
|
||||
test('tryResolveAsync returns null for missing', () async {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer);
|
||||
final scope = Scope(null);
|
||||
final result = await scope.tryResolveAsync<String>();
|
||||
expect(result, isNull);
|
||||
});
|
||||
@@ -278,90 +164,45 @@ void main() {
|
||||
// --------------------------------------------------------------------------
|
||||
group('Optional resolution and error handling', () {
|
||||
test("tryResolve returns null for missing dependency", () {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer);
|
||||
final scope = Scope(null);
|
||||
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);
|
||||
|
||||
// expect(
|
||||
// () => scope.installModules([TestModule<String>(value: "string two")]),
|
||||
// throwsA(isA<StateError>()));
|
||||
// });
|
||||
});
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
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, observer: MockObserver());
|
||||
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();
|
||||
});
|
||||
});
|
||||
// ----------------------------------------------------------------------------
|
||||
// Вспомогательные модули
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Расширенные 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);
|
||||
class TestModule<T> extends Module {
|
||||
final T value;
|
||||
final String? name;
|
||||
|
||||
await root.closeSubScope('feature');
|
||||
expect(d.disposeCount, 1); // dispose должен быть вызван
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Повторное закрытие не вызывает double-dispose
|
||||
await root.closeSubScope('feature');
|
||||
expect(d.disposeCount, 1);
|
||||
/// Вспомогательный модуль для подстановки builder'а через конструктор
|
||||
class _InlineModule extends Module {
|
||||
final void Function(Module, Scope) _builder;
|
||||
_InlineModule(this._builder);
|
||||
|
||||
// Повторное открытие 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);
|
||||
});
|
||||
});
|
||||
}
|
||||
@override
|
||||
void builder(Scope s) => _builder(this, s);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
## 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.
|
||||
|
||||
@@ -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
|
||||
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
http://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,
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -1,16 +1,10 @@
|
||||
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.1
|
||||
version: 1.1.0
|
||||
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
|
||||
- dependency-injection
|
||||
- dependency-management
|
||||
- inversion-of-control
|
||||
|
||||
environment:
|
||||
sdk: ">=3.5.2 <4.0.0"
|
||||
|
||||
@@ -1,35 +1,3 @@
|
||||
## 1.1.3-dev.8
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 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.
|
||||
|
||||
## 1.1.3-dev.4
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 1.1.3-dev.3
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 1.1.3-dev.2
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 1.1.3-dev.1
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 1.1.3-dev.0
|
||||
|
||||
- **FIX**: update deps.
|
||||
|
||||
@@ -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
|
||||
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
http://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,
|
||||
|
||||
@@ -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](https://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](http://www.apache.org/licenses/LICENSE-2.0).
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
/// https://www.apache.org/licenses/LICENSE-2.0
|
||||
/// http://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.
|
||||
|
||||
@@ -1,16 +1,10 @@
|
||||
name: cherrypick_flutter
|
||||
description: "Flutter library that allows access to the root scope through the context using `CherryPickProvider`."
|
||||
version: 1.1.3-dev.8
|
||||
version: 1.1.3-dev.0
|
||||
homepage: https://pese-git.github.io/cherrypick-site/
|
||||
documentation: https://github.com/pese-git/cherrypick/wiki
|
||||
repository: https://github.com/pese-git/cherrypick
|
||||
issue_tracker: https://github.com/pese-git/cherrypick/issues
|
||||
topics:
|
||||
- di
|
||||
- ioc
|
||||
- dependency-injection
|
||||
- dependency-management
|
||||
- inversion-of-control
|
||||
|
||||
environment:
|
||||
sdk: ">=3.5.2 <4.0.0"
|
||||
@@ -19,7 +13,7 @@ environment:
|
||||
dependencies:
|
||||
flutter:
|
||||
sdk: flutter
|
||||
cherrypick: ^3.0.0-dev.8
|
||||
cherrypick: ^3.0.0-dev.0
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
## 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.
|
||||
|
||||
@@ -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
|
||||
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
http://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,
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -2,23 +2,17 @@ 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.1
|
||||
version: 1.1.0
|
||||
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
|
||||
- dependency-injection
|
||||
- dependency-management
|
||||
- inversion-of-control
|
||||
|
||||
environment:
|
||||
sdk: ">=3.5.2 <4.0.0"
|
||||
|
||||
# Add regular dependencies here.
|
||||
dependencies:
|
||||
cherrypick_annotations: ^1.1.1
|
||||
cherrypick_annotations: ^1.1.0
|
||||
analyzer: ^7.0.0
|
||||
dart_style: ^3.0.0
|
||||
build: ^2.4.1
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// http://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.
|
||||
|
||||
@@ -177,49 +177,6 @@ final service = scope.tryResolve<OptionalService>(); // returns null if not exis
|
||||
|
||||
---
|
||||
|
||||
### Fast Dependency Lookup (Performance Improvement)
|
||||
|
||||
> **Performance Note:**
|
||||
> **Starting from version 3.0.0**, CherryPick uses a Map-based resolver index for dependency lookup. This means calls to `resolve<T>()`, `tryResolve<T>()` and similar methods are now O(1) operations, regardless of the number of modules or bindings within your scope. Previously it would iterate over all modules and bindings, which could reduce performance as your project grew. This optimization is internal and does not affect the public API or usage patterns, but significantly improves resolution speed for larger applications.
|
||||
|
||||
---
|
||||
|
||||
|
||||
## Automatic resource management: Disposable and dispose
|
||||
|
||||
CherryPick makes it easy to clean up resources for your singleton services and other objects registered in DI.
|
||||
If your class implements the `Disposable` interface, always **await** `scope.dispose()` (or `CherryPick.closeRootScope()`) when you want to free all resources in your scope — CherryPick will automatically await `dispose()` for every object that implements `Disposable` and was resolved via DI.
|
||||
This ensures safe and graceful resource management (including any async resource cleanup: streams, DB connections, sockets, etc.).
|
||||
|
||||
### Example
|
||||
|
||||
```dart
|
||||
class LoggingService implements Disposable {
|
||||
@override
|
||||
FutureOr<void> dispose() async {
|
||||
// Close files, streams, and perform async cleanup here.
|
||||
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.
|
||||
@@ -348,7 +305,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.
|
||||
@@ -391,26 +348,6 @@ 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!
|
||||
|
||||
@@ -460,16 +397,6 @@ 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
|
||||
|
||||
@@ -178,48 +178,6 @@ final service = scope.tryResolve<OptionalService>(); // вернет null, ес
|
||||
|
||||
---
|
||||
|
||||
### Быстрый поиск зависимостей (Performance Improvement)
|
||||
|
||||
> **Примечание по производительности:**
|
||||
> Начиная с версии **3.0.0**, CherryPick для поиска зависимости внутри scope использует Map-индекс. Благодаря этому методы `resolve<T>()`, `tryResolve<T>()` и аналогичные теперь работают за O(1), независимо от количества модулей и биндингов в вашем проекте. Ранее для поиска приходилось перебирать весь список вручную, что могло замедлять работу крупных приложений. Это внутреннее улучшение не меняет внешнего API или паттернов использования, но заметно ускоряет разрешение зависимостей на больших проектах.
|
||||
|
||||
---
|
||||
|
||||
## Автоматическое управление ресурсами: 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 через аннотации, что позволяет полностью избавиться от ручного внедрения зависимостей.
|
||||
@@ -393,26 +351,6 @@ 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!
|
||||
|
||||
@@ -465,15 +403,6 @@ void main() {
|
||||
|
||||
---
|
||||
|
||||
## FAQ
|
||||
|
||||
### В: Нужно ли использовать `await` для CherryPick.closeRootScope(), CherryPick.closeScope() или scope.dispose(), если ни один сервис не реализует Disposable?
|
||||
|
||||
**О:**
|
||||
Да! Даже если в данный момент ни один сервис не реализует Disposable, всегда используйте `await` при закрытии скоупа. Если в будущем потребуется добавить освобождение ресурсов через dispose, CherryPick вызовет его автоматически без изменения завершения работы ваших скоупов. Такой подход делает управление ресурсами устойчивым и безопасным для любых изменений архитектуры.
|
||||
|
||||
---
|
||||
|
||||
## Полезные ссылки
|
||||
|
||||
- [cherrypick](https://pub.dev/packages/cherrypick)
|
||||
|
||||
@@ -75,74 +75,10 @@ Example:
|
||||
// or
|
||||
final str = rootScope.tryResolve<String>();
|
||||
|
||||
// Recommended: Close the root scope & automatically release all Disposable resources
|
||||
await Cherrypick.closeRootScope();
|
||||
// Or, for advanced/manual scenarios:
|
||||
// await rootScope.dispose();
|
||||
// close main scope
|
||||
Cherrypick.closeRootScope();
|
||||
```
|
||||
|
||||
### 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
|
||||
|
||||
|
||||
|
||||
@@ -75,74 +75,10 @@ Scope - это контейнер, который хранит все дерев
|
||||
// или
|
||||
final str = rootScope.tryResolve<String>();
|
||||
|
||||
// Рекомендуется: закрывайте главный scope для автоматического освобождения всех ресурсов
|
||||
await Cherrypick.closeRootScope();
|
||||
// Или, для продвинутых/ручных сценариев:
|
||||
// await rootScope.dispose();
|
||||
// закрыть главный scope
|
||||
Cherrypick.closeRootScope();
|
||||
```
|
||||
|
||||
### Автоматическое управление ресурсами (`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 на логгере.
|
||||
|
||||
## Пример приложения
|
||||
|
||||
|
||||
|
||||
@@ -127,28 +127,28 @@ packages:
|
||||
path: "../../cherrypick"
|
||||
relative: true
|
||||
source: path
|
||||
version: "3.0.0-dev.7"
|
||||
version: "2.2.0"
|
||||
cherrypick_annotations:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "../../cherrypick_annotations"
|
||||
relative: true
|
||||
source: path
|
||||
version: "1.1.1"
|
||||
version: "1.1.0"
|
||||
cherrypick_flutter:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "../../cherrypick_flutter"
|
||||
relative: true
|
||||
source: path
|
||||
version: "1.1.3-dev.7"
|
||||
version: "1.1.2"
|
||||
cherrypick_generator:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
path: "../../cherrypick_generator"
|
||||
relative: true
|
||||
source: path
|
||||
version: "1.1.1"
|
||||
version: "1.1.0"
|
||||
clock:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@@ -2,8 +2,6 @@ import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:talker_flutter/talker_flutter.dart';
|
||||
|
||||
|
||||
import 'domain/repository/post_repository.dart';
|
||||
import 'presentation/bloc/post_bloc.dart';
|
||||
@@ -11,38 +9,26 @@ import 'router/app_router.dart';
|
||||
|
||||
part 'app.inject.cherrypick.g.dart';
|
||||
|
||||
class TalkerProvider extends InheritedWidget {
|
||||
final Talker talker;
|
||||
const TalkerProvider({required this.talker, required super.child, super.key});
|
||||
static Talker of(BuildContext context) => context.dependOnInheritedWidgetOfExactType<TalkerProvider>()!.talker;
|
||||
@override
|
||||
bool updateShouldNotify(TalkerProvider oldWidget) => oldWidget.talker != talker;
|
||||
}
|
||||
|
||||
@injectable()
|
||||
class MyApp extends StatelessWidget with _$MyApp {
|
||||
final _appRouter = AppRouter();
|
||||
final Talker talker;
|
||||
|
||||
@named('repo')
|
||||
@inject()
|
||||
late final PostRepository repository;
|
||||
|
||||
MyApp({super.key, required this.talker}) {
|
||||
MyApp({super.key}) {
|
||||
_inject(this);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return TalkerProvider(
|
||||
talker: talker,
|
||||
child: BlocProvider(
|
||||
create: (_) => PostBloc(repository),
|
||||
child: MaterialApp.router(
|
||||
routeInformationParser: _appRouter.defaultRouteParser(),
|
||||
routerDelegate: _appRouter.delegate(),
|
||||
theme: ThemeData.light(),
|
||||
),
|
||||
return BlocProvider(
|
||||
create: (_) => PostBloc(repository),
|
||||
child: MaterialApp.router(
|
||||
routeInformationParser: _appRouter.defaultRouteParser(),
|
||||
routerDelegate: _appRouter.delegate(),
|
||||
theme: ThemeData.light(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:talker_dio_logger/talker_dio_logger_interceptor.dart';
|
||||
import 'package:talker_dio_logger/talker_dio_logger_settings.dart';
|
||||
import 'package:talker_flutter/talker_flutter.dart';
|
||||
import '../data/network/json_placeholder_api.dart';
|
||||
import '../data/post_repository_impl.dart';
|
||||
import '../domain/repository/post_repository.dart';
|
||||
@@ -12,18 +9,6 @@ part 'app_module.module.cherrypick.g.dart';
|
||||
|
||||
@module()
|
||||
abstract class AppModule extends Module {
|
||||
@provide()
|
||||
@singleton()
|
||||
TalkerDioLoggerSettings talkerDioLoggerSettings() => TalkerDioLoggerSettings(
|
||||
printRequestHeaders: true,
|
||||
printResponseHeaders: true,
|
||||
printResponseMessage: true,
|
||||
);
|
||||
|
||||
@provide()
|
||||
@singleton()
|
||||
TalkerDioLogger talkerDioLogger(Talker talker, TalkerDioLoggerSettings settings) => TalkerDioLogger(talker: talker, settings: settings);
|
||||
|
||||
@instance()
|
||||
int timeout() => 1000;
|
||||
|
||||
@@ -50,8 +35,8 @@ abstract class AppModule extends Module {
|
||||
@provide()
|
||||
@singleton()
|
||||
@named('dio')
|
||||
Dio dio(@named('baseUrl') String baseUrl, TalkerDioLogger logger) =>
|
||||
Dio(BaseOptions(baseUrl: baseUrl))..interceptors.add(logger);
|
||||
Dio dio(@named('baseUrl') String baseUrl) =>
|
||||
Dio(BaseOptions(baseUrl: baseUrl));
|
||||
|
||||
@provide()
|
||||
@singleton()
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:talker_flutter/talker_flutter.dart';
|
||||
|
||||
class CoreModule extends Module {
|
||||
final Talker _talker;
|
||||
|
||||
CoreModule({required Talker talker}) : _talker = talker;
|
||||
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<Talker>().toProvide(() => _talker).singleton();
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user