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.
This commit is contained in:
Erik Cederberg 2022-06-15 01:16:40 +02:00 committed by GitHub
parent ce957ab42a
commit c8fb73ef83
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 1 deletions

View File

@ -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

View File

@ -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()