From c8fb73ef833b3f8bb1119b5fceea9c27394ced57 Mon Sep 17 00:00:00 2001 From: Erik Cederberg Date: Wed, 15 Jun 2022 01:16:40 +0200 Subject: [PATCH] Do not check parent binder for `AssistedBuilder` (#196) Only check the current binder for bindings when resolving `AssistedBuilder` instances, since any injected argument to the built class should use the active injector when creating the `AssistedBuilder` and not one of its parents. Fixes #186. --- injector/__init__.py | 3 ++- injector_test.py | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/injector/__init__.py b/injector/__init__.py index 731c1c1..a62afbd 100644 --- a/injector/__init__.py +++ b/injector/__init__.py @@ -632,8 +632,9 @@ class Binder: def get_binding(self, interface: type) -> Tuple[Binding, 'Binder']: is_scope = isinstance(interface, type) and issubclass(interface, Scope) + is_assisted_builder = _is_specialization(interface, AssistedBuilder) try: - return self._get_binding(interface, only_this_binder=is_scope) + return self._get_binding(interface, only_this_binder=is_scope or is_assisted_builder) except (KeyError, UnsatisfiedRequirement): if is_scope: scope = interface diff --git a/injector_test.py b/injector_test.py index 76e9bd2..80cca82 100644 --- a/injector_test.py +++ b/injector_test.py @@ -805,6 +805,19 @@ def test_assisted_builder_injection_is_safe_to_use_with_multiple_injectors(): assert (b1._injector, b2._injector) == (i1, i2) +def test_assisted_builder_injection_is_safe_to_use_with_child_injectors(): + class X: + @inject + def __init__(self, builder: AssistedBuilder[NeedsAssistance]): + self.builder = builder + + i1 = Injector() + i2 = i1.create_child_injector() + b1 = i1.get(X).builder + b2 = i2.get(X).builder + assert (b1._injector, b2._injector) == (i1, i2) + + class TestThreadSafety: def setup(self): self.event = threading.Event()