diff --git a/docs/providers/dependency.rst b/docs/providers/dependency.rst index 6924f137..4436b577 100644 --- a/docs/providers/dependency.rst +++ b/docs/providers/dependency.rst @@ -15,7 +15,12 @@ Dependency provider will control that returned object is an instance of ``instan To provide a dependency you need to override the ``Dependency`` provider. You can call provider ``.override()`` method or provide an overriding provider when creating a container. -See :ref:`provider-overriding`. +See :ref:`provider-overriding`. If you don't provide a dependency, ``Dependency`` provider +will raise an error: + +.. literalinclude:: ../../examples/providers/dependency_undefined_error.py + :language: python + :lines: 18- You also can provide a default for the dependency. To provide a default use ``default`` argument: ``Dependency(..., default=...)``. Default can be a value or a provider. If default is not a provider, diff --git a/examples/providers/dependency.py b/examples/providers/dependency.py index a1114cba..c1b7b03f 100644 --- a/examples/providers/dependency.py +++ b/examples/providers/dependency.py @@ -3,7 +3,7 @@ import abc import dataclasses -from dependency_injector import containers, providers, errors +from dependency_injector import containers, providers class DbAdapter(metaclass=abc.ABCMeta): @@ -41,10 +41,5 @@ if __name__ == '__main__': assert isinstance(container2.user_service().database, PostgresDbAdapter) container3 = Container(database=providers.Singleton(object)) - try: - container3.user_service() - except errors.Error as exception: - print(exception) - # The output is: - # is not an - # instance of + container3.user_service() # <-- raises error: + # is not an instance of DbAdapter diff --git a/examples/providers/dependency_undefined_error.py b/examples/providers/dependency_undefined_error.py new file mode 100644 index 00000000..d7ee2cbc --- /dev/null +++ b/examples/providers/dependency_undefined_error.py @@ -0,0 +1,31 @@ +"""`Dependency` provider undefined error example.""" + +import abc +import dataclasses + +from dependency_injector import containers, providers + + +class DbAdapter(metaclass=abc.ABCMeta): + ... + + +@dataclasses.dataclass +class UserService: + database: DbAdapter + + +class Container(containers.DeclarativeContainer): + + database = providers.Dependency(instance_of=DbAdapter) + + user_service = providers.Factory( + UserService, + database=database, + ) + + +if __name__ == '__main__': + container = Container() + container.user_service() # <-- raises error: + # Dependency "Container.database" is not defined