2020-08-16 05:09:41 +03:00
|
|
|
"""Creation of dynamic container based on the configuration example."""
|
2016-06-06 11:26:53 +03:00
|
|
|
|
2020-08-16 05:09:41 +03:00
|
|
|
from dependency_injector import containers, providers
|
2016-06-08 16:52:58 +03:00
|
|
|
|
2016-06-06 11:26:53 +03:00
|
|
|
|
2020-08-16 05:09:41 +03:00
|
|
|
class UserService:
|
|
|
|
...
|
2016-06-06 11:26:53 +03:00
|
|
|
|
|
|
|
|
2020-08-16 05:09:41 +03:00
|
|
|
class AuthService:
|
|
|
|
...
|
2016-06-06 11:26:53 +03:00
|
|
|
|
|
|
|
|
2020-08-16 05:09:41 +03:00
|
|
|
def populate_container(container, providers_config):
|
|
|
|
for provider_name, provider_info in providers_config.items():
|
|
|
|
provided_cls = globals().get(provider_info['class'])
|
|
|
|
provider_cls = getattr(providers, provider_info['provider_class'])
|
|
|
|
setattr(container, provider_name, provider_cls(provided_cls))
|
2016-06-06 11:26:53 +03:00
|
|
|
|
|
|
|
|
2020-08-16 05:09:41 +03:00
|
|
|
if __name__ == '__main__':
|
|
|
|
services_config = {
|
|
|
|
'user': {
|
|
|
|
'class': 'UserService',
|
|
|
|
'provider_class': 'Factory',
|
2016-06-06 11:26:53 +03:00
|
|
|
},
|
|
|
|
'auth': {
|
2020-08-16 05:09:41 +03:00
|
|
|
'class': 'AuthService',
|
|
|
|
'provider_class': 'Factory',
|
|
|
|
},
|
2016-06-06 11:26:53 +03:00
|
|
|
}
|
2020-08-16 05:09:41 +03:00
|
|
|
services = containers.DynamicContainer()
|
2016-06-06 11:26:53 +03:00
|
|
|
|
2020-08-16 05:09:41 +03:00
|
|
|
populate_container(services, services_config)
|
2016-06-06 11:26:53 +03:00
|
|
|
|
2020-08-16 05:09:41 +03:00
|
|
|
user_service = services.user()
|
|
|
|
auth_service = services.auth()
|
2016-06-06 11:26:53 +03:00
|
|
|
|
2020-08-16 05:09:41 +03:00
|
|
|
assert isinstance(user_service, UserService)
|
|
|
|
assert isinstance(auth_service, AuthService)
|