python-dependency-injector/examples/containers/dynamic_runtime_creation.py

41 lines
1.0 KiB
Python
Raw Normal View History

"""Creation of dynamic container based on the configuration example."""
from dependency_injector import containers, providers
class UserService:
...
class AuthService:
...
def populate_container(container, providers_config):
for provider_name, provider_info in providers_config.items():
2021-09-30 22:16:17 +03:00
provided_cls = globals().get(provider_info["class"])
provider_cls = getattr(providers, provider_info["provider_class"])
setattr(container, provider_name, provider_cls(provided_cls))
2021-09-30 22:16:17 +03:00
if __name__ == "__main__":
services_config = {
2021-09-30 22:16:17 +03:00
"user": {
"class": "UserService",
"provider_class": "Factory",
},
2021-09-30 22:16:17 +03:00
"auth": {
"class": "AuthService",
"provider_class": "Factory",
},
}
services = containers.DynamicContainer()
populate_container(services, services_config)
user_service = services.user()
auth_service = services.auth()
assert isinstance(user_service, UserService)
assert isinstance(auth_service, AuthService)