2021-02-14 23:47:15 +00:00
|
|
|
.. _dependency-provider:
|
|
|
|
|
2020-09-02 01:39:23 +00:00
|
|
|
Dependency provider
|
2020-09-02 21:33:02 +00:00
|
|
|
===================
|
2015-06-18 13:34:26 +00:00
|
|
|
|
2015-11-29 21:30:48 +00:00
|
|
|
.. currentmodule:: dependency_injector.providers
|
2015-11-23 14:48:21 +00:00
|
|
|
|
2021-01-29 18:49:40 +00:00
|
|
|
:py:class:`Dependency` provider is a placeholder for a dependency of a certain type.
|
2015-06-18 13:34:26 +00:00
|
|
|
|
2021-01-29 18:49:40 +00:00
|
|
|
To specify a type of the dependency use ``instance_of`` argument: ``Dependency(instance_of=SomeClass)``.
|
|
|
|
Dependency provider will control that returned object is an instance of ``instance_of`` type.
|
2015-06-18 13:34:26 +00:00
|
|
|
|
2017-12-21 20:54:44 +00:00
|
|
|
.. literalinclude:: ../../examples/providers/dependency.py
|
2015-08-03 12:45:58 +00:00
|
|
|
:language: python
|
2020-09-02 01:39:23 +00:00
|
|
|
:lines: 3-
|
2021-01-29 18:49:40 +00:00
|
|
|
:emphasize-lines: 26,35-36
|
|
|
|
|
|
|
|
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.
|
2021-02-13 14:16:38 +00:00
|
|
|
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-
|
2021-01-29 18:49:40 +00:00
|
|
|
|
|
|
|
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,
|
|
|
|
dependency provider will wrap it into the ``Object`` provider.
|
|
|
|
|
|
|
|
.. literalinclude:: ../../examples/providers/dependency_default.py
|
|
|
|
:language: python
|
|
|
|
:lines: 16-23
|
|
|
|
:emphasize-lines: 3
|
2017-02-28 20:07:12 +00:00
|
|
|
|
2021-02-14 23:47:15 +00:00
|
|
|
See also: :ref:`check-container-dependencies`.
|
|
|
|
|
2017-02-28 20:07:12 +00:00
|
|
|
.. disqus::
|