From f7cc86ea66a6e1e0f09880f4635f27b039087675 Mon Sep 17 00:00:00 2001 From: Sergey Penkovsky Date: Wed, 30 Jul 2025 13:16:23 +0300 Subject: [PATCH] docs: add quick guide for circular dependency detection to README --- cherrypick/README.md | 71 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 69 insertions(+), 2 deletions(-) diff --git a/cherrypick/README.md b/cherrypick/README.md index 0c19c5d..162b2b8 100644 --- a/cherrypick/README.md +++ b/cherrypick/README.md @@ -8,7 +8,6 @@ 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 @@ -239,6 +238,74 @@ class ApiClientImpl implements ApiClient { - [x] Null-safe Resolution (tryResolve/tryResolveAsync) - [x] Circular Dependency Detection (Local and Global) +## Quick Guide: 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().to((s) => A(s.resolve())); + bind().to((s) => B(s.resolve())); + }), +]); + +scope.resolve(); // 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(); +} on CircularDependencyException catch (e) { + print('Dependency chain: ${e.dependencyChain}'); +} +``` + +**More details:** See [cycle_detection.en.md](doc/cycle_detection.en.md) + ## Documentation - [Circular Dependency Detection (English)](doc/cycle_detection.en.md) @@ -258,4 +325,4 @@ Licensed under the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2 ## Links -- [GitHub Repository](https://github.com/pese-git/cherrypick) \ No newline at end of file +- [GitHub Repository](https://github.com/pese-git/cherrypick)