mirror of
https://github.com/ets-labs/python-dependency-injector.git
synced 2025-02-05 14:10:49 +03:00
Update docs
This commit is contained in:
parent
3e4667e2fe
commit
476a893c6c
|
@ -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::
|
||||
|
|
25
examples/providers/dependency_default.py
Normal file
25
examples/providers/dependency_default.py
Normal 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)
|
Loading…
Reference in New Issue
Block a user