ets-labs/python-dependency-injector

How to access the config in case of container copying

Opened this issue · 1 comments

Hi there,

I have the Common container and there is a config. I create New container by copying of the Common container. How can I get access to the config from the Common container? Here is en example:

import asyncio
from dependency_injector import containers, providers


class API:
    def __init__(self, name) -> None:
        print(f"name: {name}")


class Common(containers.DeclarativeContainer):
    config = providers.Configuration()

    api = providers.Singleton(API, name=config.name)


@containers.copy(Common)
class New(Common):
    __self__ = providers.Self()

    api2 = providers.Singleton(API, name=__self__.provided.config.name)


def main():
    config = providers.Configuration()
    config.name.from_value("Bob")

    container = New(config=config)
    container.api()
    print("--------")
    container.api2()


if __name__ == "__main__":
    main()

Output:

name: Bob
--------
name: config

I expected that somewhere within __self__ should be the configuration that was passed into the new container.

But when the container is ready I can see the config through __self__:

container.__self__.provided().config.name()
'Bob'
container.config.name()
'Bob'