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,17 +52,26 @@ class ServiceProvider(ServiceProviderABC):
def get_db_context(self) -> Callable[DatabaseContextABC]:
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):
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):
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:
if type(known_service) == service_type:
raise Exception(f'Service with type {service_type} already exists')
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]:

View File

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