Aggregate provider

Aggregate provider aggregates a group of other providers.

from dependency_injector import containers, providers


class ConfigReader:

    def __init__(self, path):
        self._path = path

    def read(self):
        print(f"Parsing {self._path} with {self.__class__.__name__}")
        ...


class YamlReader(ConfigReader):
    ...


class JsonReader(ConfigReader):
    ...


class Container(containers.DeclarativeContainer):

    config_readers = providers.Aggregate(
        yaml=providers.Factory(YamlReader),
        json=providers.Factory(JsonReader),
    )


if __name__ == "__main__":
    container = Container()

    yaml_reader = container.config_readers("yaml", "./config.yml")
    yaml_reader.read()  # Parsing ./config.yml with YamlReader

    json_reader = container.config_readers("json", "./config.json")
    json_reader.read()  # Parsing ./config.json with JsonReader

Each provider in the Aggregate is associated with a key. You can call aggregated providers by providing their key as a first argument. All positional and keyword arguments following the key will be forwarded to the called provider:

yaml_reader = container.config_readers("yaml", "./config.yml", foo=...)

You can also retrieve an aggregated provider by providing its key as an attribute name:

yaml_reader = container.config_readers.yaml("./config.yml", foo=...)

To retrieve a dictionary of aggregated providers, use .providers attribute:

container.config_readers.providers == {
    "yaml": <YAML provider>,
    "json": <JSON provider>,
}

Note

You can not override the Aggregate provider.

Note

When you inject the Aggregate provider, it is passed “as is”.

To use non-string keys or string keys with . and -, provide a dictionary as a positional argument:

aggregate = providers.Aggregate({
    SomeClass: providers.Factory(...),
    "key.with.periods": providers.Factory(...),
    "key-with-dashes": providers.Factory(...),
})

See also

Selector provider to make injections based on a configuration value, environment variable, or a result of a callable.

Aggregate provider is different from the Selector provider. Aggregate provider doesn’t select which provider to inject and doesn’t have a selector. It is a group of providers and is always injected “as is”. The rest of the interface of both providers is similar.

Note

Aggregate provider is a successor of Factory aggregate provider. Aggregate provider doesn’t have a restriction on the provider type, while FactoryAggregate aggregates only Factory providers.