Update docs

This commit is contained in:
Roman Mogylatov 2021-01-29 13:44:24 -05:00
parent 3e4667e2fe
commit 476a893c6c
2 changed files with 39 additions and 5 deletions

View File

@ -8,13 +8,22 @@ Dependency provider
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.
The ``Dependency`` provider must be overridden before usage. It can be overridden by any type of
the provider. The only rule is that overriding provider must return an instance of ``instance_of``
dependency type.
.. literalinclude:: ../../examples/providers/dependency.py
:language: python
:lines: 3-
:emphasize-lines: 26
: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.
See :ref:`provider-overriding`.
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
.. disqus::

View File

@ -0,0 +1,25 @@
"""`Dependency` provider default example."""
import abc
from dependency_injector import containers, providers
class Cache(metaclass=abc.ABCMeta):
...
class InMemoryCache(Cache):
...
class Container(containers.DeclarativeContainer):
cache = providers.Dependency(instance_of=Cache, default=InMemoryCache())
if __name__ == '__main__':
container = Container()
cache = container.cache() # provides InMemoryCache()
assert isinstance(cache, InMemoryCache)