Selector providersΒΆ

Selector provider selects provider based on the configuration value or other callable.

from dependency_injector import providers


config = providers.Configuration()

selector = providers.Selector(
    config.one_or_another,
    one=providers.Factory(SomeClass),
    another=providers.Factory(SomeOtherClass),
)

Selector provider has a callable called selector and a dictionary of providers.

The selector callable is provided as a first positional argument. It can be Configuration provider or any other callable. It has to return a string value. This value is used as a key for selecting the provider from the dictionary of providers.

The providers are provided as keyword arguments. Argument name is used as a key for selecting the provider.

Full example:

from dependency_injector import providers


class SomeClass:
    ...


class SomeOtherClass:
    ...


config = providers.Configuration()

selector = providers.Selector(
    config.one_or_another,
    one=providers.Factory(SomeClass),
    another=providers.Factory(SomeOtherClass),
)

config.override({'one_or_another': 'one'})
instance_1 = selector()
assert isinstance(instance_1, SomeClass)

config.override({'one_or_another': 'another'})
instance_2 = selector()
assert isinstance(instance_2, SomeOtherClass)