Skip to content

Commit

Permalink
Do not check parent binder for AssistedBuilder (#196)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
erikced committed Jun 14, 2022
1 parent ce957ab commit c8fb73e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
3 changes: 2 additions & 1 deletion injector/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -632,8 +632,9 @@ def _get_binding(self, key: type, *, only_this_binder: bool = False) -> Tuple[Bi

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
Expand Down
13 changes: 13 additions & 0 deletions injector_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -805,6 +805,19 @@ def __init__(self, builder: AssistedBuilder[NeedsAssistance]):
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()
Expand Down

0 comments on commit c8fb73e

Please sign in to comment.