mirror of
https://github.com/ets-labs/python-dependency-injector.git
synced 2025-03-26 12:54:24 +03:00
Add example and docs
This commit is contained in:
parent
139279f26a
commit
f3ca03e569
|
@ -21,4 +21,20 @@ The container also has:
|
|||
|
||||
:py:class:`DynamicContainer` has the same functionality.
|
||||
|
||||
Another possible way to override container providers on declarative level is
|
||||
``@containers.override()`` decorator:
|
||||
|
||||
.. literalinclude:: ../../examples/containers/declarative_override_decorator.py
|
||||
:language: python
|
||||
:lines: 3-
|
||||
:emphasize-lines: 12-16
|
||||
|
||||
Decorator ``@containers.override()`` takes a container for overriding as an argument.
|
||||
This container providers will be overridden by the providers with the same names from
|
||||
the decorated container.
|
||||
|
||||
It helps to change the behaviour of application by importing extension modules but not a code change.
|
||||
Imported module can override providers in main container. While the code uses main container as
|
||||
before, the overridden providers provide components defined in the extension module.
|
||||
|
||||
.. disqus::
|
||||
|
|
25
examples/containers/declarative_override_decorator.py
Normal file
25
examples/containers/declarative_override_decorator.py
Normal file
|
@ -0,0 +1,25 @@
|
|||
"""Declarative container provider overriding with `@override()` decorator."""
|
||||
|
||||
import sqlite3
|
||||
from unittest import mock
|
||||
|
||||
from dependency_injector import containers, providers
|
||||
|
||||
|
||||
class Container(containers.DeclarativeContainer):
|
||||
|
||||
database = providers.Singleton(sqlite3.connect, ':memory:')
|
||||
|
||||
|
||||
# Overriding `Container` with `OverridingContainer`:
|
||||
@containers.override(Container)
|
||||
class OverridingContainer(containers.DeclarativeContainer):
|
||||
|
||||
database = providers.Singleton(mock.Mock)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
container = Container()
|
||||
|
||||
database = container.database()
|
||||
assert isinstance(database, mock.Mock)
|
Loading…
Reference in New Issue
Block a user