Selector provider — Dependency Injector 4.46.0 documentation (original) (raw)
Selector provider selects provider based on a configuration value or another callable.
from dependency_injector import containers, providers
class SomeClass: ...
class SomeOtherClass: ...
class Container(containers.DeclarativeContainer):
config = providers.Configuration()
selector = providers.Selector(
config.one_or_another,
one=providers.Factory(SomeClass),
another=providers.Factory(SomeOtherClass),
)
if name == "main": container = Container()
container.config.override({"one_or_another": "one"})
instance_1 = container.selector()
assert isinstance(instance_1, SomeClass)
container.config.override({"one_or_another": "another"})
instance_2 = container.selector()
assert isinstance(instance_2, SomeOtherClass)
The first argument of the Selector
provider is called selector
. It can be an option of a Configuration
provider or any other callable. The selector
callable has to return a string value. This value is used as a key for selecting the provider.
The providers are provided as keyword arguments. Argument name is used as a key for selecting the provider.
When a Selector
provider is called, it gets a selector
value and delegates the work to the provider with a matching name. The selector
callable works as a switch: when the returned value is changed the Selector
provider will delegate the work to another provider.