Common: Raise TypeError if DIContainer.register() called with instance

This commit is contained in:
Mike Salvatore 2022-04-26 02:32:02 -04:00
parent 9b52f3f21b
commit 8c3477a000
2 changed files with 13 additions and 0 deletions

View File

@ -25,6 +25,13 @@ class DIContainer:
:param interface: An interface or abstract base class that other classes depend upon :param interface: An interface or abstract base class that other classes depend upon
:param concrete_type: A type (class) that implements `interface` :param concrete_type: A type (class) that implements `interface`
""" """
if not inspect.isclass(concrete_type):
raise TypeError(
"Expected a class, but received an instance of type "
f'"{concrete_type.__class__.__name__}"; Pass a class, not an instance, to '
"register(), or use register_instance() instead."
)
self._type_registry[interface] = concrete_type self._type_registry[interface] = concrete_type
DIContainer._del_key(self._instance_registry, interface) DIContainer._del_key(self._instance_registry, interface)

View File

@ -260,3 +260,9 @@ def test_resolve_dependencies(container):
assert isinstance(dependencies[0], ServiceA) assert isinstance(dependencies[0], ServiceA)
assert isinstance(dependencies[1], ServiceB) assert isinstance(dependencies[1], ServiceB)
def test_register_instance_as_type(container):
service_a_instance = ServiceA()
with pytest.raises(TypeError):
container.register(IServiceA, service_a_instance)