Skip to content

Support scopes for multibind types #283

@davidparsson

Description

@davidparsson

Tasks spawned from related discussion in #277 (comment):

  1. Respect scopes in when getting items in multibind lists/dicts. Described by the first test case below.
  2. Repurpose the scope argument to injector.multibind(), to apply the scope to the element(s) being added instead of the list/dict. Described by the second test case below.

Open question: Should binder.multibind(List[Plugin], to=PluginA, scope=singleton) make injector.get(PluginA) return the same singleton?

Test case idéas:

def test_multibind_types_respect_the_bound_type_scope() -> None:
    def configure(binder: Binder) -> None:
        binder.bind(PluginA, to=PluginA, scope=singleton)
        binder.multibind(List[Plugin], to=PluginA)

    injector = Injector([configure])
    first_list = injector.get(List[Plugin])
    second_list = injector.get(List[Plugin])

    assert first_list[0] is second_list[0]


def test_multibind_scopes_applies_to_the_bound_items() -> None:
    def configure(binder: Binder) -> None:
        binder.multibind(List[Plugin], to=PluginA, scope=singleton)
        binder.multibind(List[Plugin], to=PluginB)
        binder.multibind(List[Plugin], to=PluginC, scope=singleton)

    injector = Injector([configure])
    first_list = injector.get(List[Plugin])
    second_list = injector.get(List[Plugin])

    assert first_list is not second_list
    assert first_list[0] is second_list[0]
    assert first_list[1] is not second_list[1]
    assert first_list[2] is second_list[2]


def test_multibind_scopes_does_not_apply_to_the_type_globally() -> None:
    def configure(binder: Binder) -> None:
        binder.multibind(List[Plugin], to=PluginA, scope=singleton)

    injector = Injector([configure])
    plugins = injector.get(List[Plugin])

    assert plugins[0] is not injector.get(PluginA)
    assert plugins[0] is not injector.get(Plugin)
    assert injector.get(PluginA) is not injector.get(PluginA)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions