From 7382407be07c53dbd80dbc5a94e79d42778ef468 Mon Sep 17 00:00:00 2001 From: Mike Salvatore Date: Tue, 26 Apr 2022 01:37:41 -0400 Subject: [PATCH] Common: Add DIContainer.resolve_dependencies() --- monkey/common/di_container.py | 18 +++++++++++++++--- .../unit_tests/common/test_di_container.py | 10 ++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/monkey/common/di_container.py b/monkey/common/di_container.py index 4ad246ec7..9642ffb1f 100644 --- a/monkey/common/di_container.py +++ b/monkey/common/di_container.py @@ -1,5 +1,5 @@ import inspect -from typing import Any, MutableMapping, Type, TypeVar +from typing import Any, MutableMapping, Sequence, Type, TypeVar T = TypeVar("T") @@ -40,7 +40,7 @@ class DIContainer: injection. Note that only positional arguments are resolved. Varargs, keyword-only args, and default values are ignored. - :param type_: A type (class) to construct. + :param type_: A type (class) to construct :return: An instance of `type_` """ try: @@ -48,13 +48,25 @@ class DIContainer: except ValueError: pass + args = self.resolve_dependencies(type_) + return type_(*args) + + def resolve_dependencies(self, type_: Type[T]) -> Sequence[Any]: + """ + Resolves all dependencies of type_ and returns a Sequence of objects that correspond type_'s + dependencies. Note that only positional arguments are resolved. Varargs, keyword-only args, + and default values are ignored. + + :param type_: A type (class) to resolve dependencies for + :return: An Sequence of dependencies to be injected into type_'s constructor + """ args = [] for arg_type in inspect.getfullargspec(type_).annotations.values(): instance = self._resolve_type(arg_type) args.append(instance) - return type_(*args) + return tuple(args) def _resolve_type(self, type_: Type[T]) -> T: if type_ in self._type_registry: diff --git a/monkey/tests/unit_tests/common/test_di_container.py b/monkey/tests/unit_tests/common/test_di_container.py index dab1a8f29..1d1e4ea5c 100644 --- a/monkey/tests/unit_tests/common/test_di_container.py +++ b/monkey/tests/unit_tests/common/test_di_container.py @@ -250,3 +250,13 @@ def test_resolve_registered_instance(container): service_a_actual_instance = container.resolve(IServiceA) assert id(service_a_actual_instance) == id(service_a_instance) + + +def test_resolve_dependencies(container): + container.register(IServiceA, ServiceA) + container.register(IServiceB, ServiceB) + + dependencies = container.resolve_dependencies(TestClass3) + + assert isinstance(dependencies[0], ServiceA) + assert isinstance(dependencies[1], ServiceB)