Improved service providing

This commit is contained in:
Sven Heidemann 2021-03-04 17:55:15 +01:00
parent 956a107d38
commit 01ef965180
2 changed files with 18 additions and 9 deletions

View File

@ -52,18 +52,27 @@ class ServiceProvider(ServiceProviderABC):
def get_db_context(self) -> Callable[DatabaseContextABC]: def get_db_context(self) -> Callable[DatabaseContextABC]:
return self._database_context return self._database_context
def add_transient(self, service_type: Type[ServiceABC], service: Callable[ServiceABC]): def add_transient(self, service_type: Type[ServiceABC], service: Callable[ServiceABC] = None):
self._transient_services[service_type] = service if service is None:
self._transient_services[service_type] = service_type
else:
self._transient_services[service_type] = service
def add_scoped(self, service_type: Type[ServiceABC], service: Callable[ServiceABC]): def add_scoped(self, service_type: Type[ServiceABC], service: Callable[ServiceABC] = None):
self._scoped_services[service_type] = service if service is None:
self._scoped_services[service_type] = service_type
else:
self._scoped_services[service_type] = service
def add_singleton(self, service_type: Type[ServiceABC], service: Callable[ServiceABC]): def add_singleton(self, service_type: Type[ServiceABC], service: Callable[ServiceABC] = None):
for known_service in self._singleton_services: for known_service in self._singleton_services:
if type(known_service) == service_type: if type(known_service) == service_type:
raise Exception(f'Service with type {service_type} already exists') raise Exception(f'Service with type {service_type} already exists')
self._singleton_services[service_type] = self._create_instance(service) if service is None:
self._singleton_services[service_type] = self._create_instance(service_type)
else:
self._singleton_services[service_type] = self._create_instance(service)
def get_service(self, instance_type: Type) -> Callable[ServiceABC]: def get_service(self, instance_type: Type) -> Callable[ServiceABC]:
for service in self._transient_services: for service in self._transient_services:

View File

@ -18,13 +18,13 @@ class ServiceProviderABC(ABC):
def get_db_context(self) -> Callable[DatabaseContextABC]: pass def get_db_context(self) -> Callable[DatabaseContextABC]: pass
@abstractmethod @abstractmethod
def add_transient(self, service_type: Type, service: Callable): pass def add_transient(self, service_type: Type, service: Callable = None): pass
@abstractmethod @abstractmethod
def add_scoped(self, service_type: Type, service: Callable): pass def add_scoped(self, service_type: Type, service: Callable = None): pass
@abstractmethod @abstractmethod
def add_singleton(self, service_type: Type, service: Callable): pass def add_singleton(self, service_type: Type, service: Callable = None): pass
@abstractmethod @abstractmethod
def get_service(self, instance_type: Type) -> Callable[ServiceABC]: pass def get_service(self, instance_type: Type) -> Callable[ServiceABC]: pass