diff --git a/cherrypick/README.md b/cherrypick/README.md index ba863cd..e65a4dc 100644 --- a/cherrypick/README.md +++ b/cherrypick/README.md @@ -185,6 +185,15 @@ void builder(Scope scope) { > Use this pattern only when you want a “master” singleton. If you expect a new instance per params, **do not** use `.singleton()` on parameterized providers. +> ℹ️ **Note about `.singleton()` and `.toInstance()`:** +> +> Calling `.singleton()` after `.toInstance()` does **not** change the binding’s behavior: the object passed with `toInstance()` is already a single, constant instance that will be always returned for every resolve. +> +> It is not necessary to use `.singleton()` with an existing object—this call has no effect. +> +> `.singleton()` is only meaningful with providers (such as `toProvide`/`toProvideAsync`), to ensure only one instance is created by the factory. + + ### Module A **Module** is a logical collection point for bindings, designed for grouping and initializing related dependencies. Implement the `builder` method to define how dependencies should be bound within the scope. diff --git a/cherrypick/lib/src/binding.dart b/cherrypick/lib/src/binding.dart index e0c2c65..fd369d9 100644 --- a/cherrypick/lib/src/binding.dart +++ b/cherrypick/lib/src/binding.dart @@ -258,6 +258,13 @@ class Binding { /// ``` /// /// Use this pattern only if you want a master singleton. If you expect a new instance per params, **do not** use `.singleton()` on parameterized providers. + /// + /// ℹ️ **Note about `.singleton()` and `.toInstance()`:** + /// + /// Calling `.singleton()` after `.toInstance()` does **not** change the binding’s behavior: + /// the object passed with `toInstance()` is already a single, constant instance that will always be returned for every resolve. + /// There is no need to use `.singleton()` with `toInstance()`. This call has no effect. + /// `.singleton()` is only meaningful with providers (`toProvide`, `toProvideAsync`, etc), to ensure only one instance is created by the factory. Binding singleton() { _resolver?.toSingleton(); return this; diff --git a/doc/full_tutorial_en.md b/doc/full_tutorial_en.md index d71f7d3..dd13f50 100644 --- a/doc/full_tutorial_en.md +++ b/doc/full_tutorial_en.md @@ -107,6 +107,14 @@ final api = scope.resolve(named: 'mock'); - `.singleton()` — single instance per Scope lifetime - By default, every resolve creates a new object +> ℹ️ **Note about `.singleton()` and `.toInstance()`:** +> +> Calling `.singleton()` after `.toInstance()` does **not** change the binding’s behavior: the object passed with `toInstance()` is already a single, constant instance that will be always returned for every resolve. +> +> It is not necessary to use `.singleton()` with an existing object—this call has no effect. +> +> `.singleton()` is only meaningful with providers (such as `toProvide`/`toProvideAsync`), to ensure only one instance is created by the factory. + ### Parameterized bindings Allows you to create dependencies with runtime parameters, e.g., a service for a user with a given ID: diff --git a/doc/full_tutorial_ru.md b/doc/full_tutorial_ru.md index 2590661..52b758d 100644 --- a/doc/full_tutorial_ru.md +++ b/doc/full_tutorial_ru.md @@ -44,6 +44,7 @@ final setupFuture = loadEnvironment(); bind().toInstanceAsync(setupFuture); ``` + > ⚠️ **Важное примечание по использованию toInstance в Module** > > Если вы регистрируете цепочку зависимостей через `toInstance` внутри метода `builder` вашего `Module`, нельзя в это же время вызывать `scope.resolve()` для только что объявленного типа. @@ -85,6 +86,7 @@ bind().toInstanceAsync(setupFuture); > **Примечание:** Это ограничение касается только `toInstance`. Для провайдеров (`toProvide`/`toProvideAsync`) и других стратегий вы можете использовать `scope.resolve()` внутри builder без ограничений. + - **toProvide** — обычная синхронная фабрика. - **toProvideAsync** — асинхронная фабрика (например, если нужно дожидаться Future). - **toProvideWithParams / toProvideAsyncWithParams** — фабрики с параметрами. @@ -108,6 +110,15 @@ final api = scope.resolve(named: 'mock'); - `.singleton()` — один инстанс на всё время жизни Scope. - По умолчанию каждый resolve создаёт новый объект. +> ℹ️ **Примечание о `.singleton()` и `.toInstance()`:** +> +> Вызов `.singleton()` после `.toInstance()` не изменяет поведения биндинга: объект, переданный через `toInstance()`, и так всегда будет "единственным" (single instance), возвращаемым при каждом resolve. +> +> Применять `.singleton()` к уже существующему объекту нет необходимости — этот вызов ничего не меняет. +> +> `.singleton()` нужен только для провайдеров (например, `toProvide`/`toProvideAsync`), чтобы зафиксировать единственный экземпляр, создаваемый фабрикой. + + ### Параметрические биндинги Позволяют создавать зависимости с runtime-параметрами — например, сервис для пользователя с ID: