python-dependency-injector
python-dependency-injector copied to clipboard
Object provider for an item from a dict-like provider using configuration provider value
trafficstars
I’m trying to setup a direct provider to my db instance. My mongo client is properly initialized and provide a dict-like interface for me to reach my database. I only need to access it using a string key. I’ve try the object provider without success as shown in bellow example.
Unfortunately i’m stuck with this pattern, since the key is the dependency injector ItemGetter, not its value. How should I use the api to resolve my use case ?
from dependency_injector import providers, containers
class Container(containers.DeclarativeContainer):
config = providers.Configuration()
mongo_client = providers.Dict(foo="foo database", bar="bar database")
mongo_database = providers.Object(
# The faulty behaviour is here, i really don’t know how to dynamically access a provider using a provided key.
mongo_client.provided[config.provided["db"]["database"]]
)
if __name__ == "__main__":
container = Container()
container.config.from_dict({"db": {"database": "foo"}})
# That’s not the string but a dependency_injector.providers.ItemGetter()
assert container.mongo_database() == "foo database"
I’ve found a solution, could it be the proper way ?
I’m using the Self provider and a callback provider.
from dependency_injector import providers, containers
def get_database(container=containers.DeclarativeContainer):
client = container.mongo_client()
dbname = container.config.db.database()
return client[dbname]
class Container(containers.DeclarativeContainer):
__self__ = providers.Self()
config = providers.Configuration()
mongo_client = providers.Dict(foo="foo collection", bar="bar collection")
mongo_database = providers.Callable(get_database, container=__self__)
if __name__ == "__main__":
container = Container()
container.config.from_dict({"db": {"database": "foo"}})
# That’s not the string but a dependency_injector.providers.ItemGetter()
assert container.mongo_database() == "foo collection"