2020-09-03 04:21:18 +03:00
|
|
|
Container overriding
|
|
|
|
--------------------
|
2015-10-11 15:34:21 +03:00
|
|
|
|
2016-06-03 00:48:06 +03:00
|
|
|
.. currentmodule:: dependency_injector.containers
|
2015-11-20 19:52:19 +03:00
|
|
|
|
2020-08-16 08:10:08 +03:00
|
|
|
The container can be overridden by the other container. All of the providers from the overriding
|
|
|
|
container will override the providers with the same names in the overridden container.
|
2015-10-11 15:34:21 +03:00
|
|
|
|
2020-08-16 08:10:08 +03:00
|
|
|
.. literalinclude:: ../../examples/containers/override.py
|
2015-10-11 15:34:21 +03:00
|
|
|
:language: python
|
2020-08-16 08:10:08 +03:00
|
|
|
:lines: 3-
|
2015-10-11 15:34:21 +03:00
|
|
|
|
2020-08-16 08:10:08 +03:00
|
|
|
It helps in a testing. Also you can use it for configuring project for the different
|
|
|
|
environments: replace an API client with a stub on the dev or stage.
|
2015-11-20 19:52:19 +03:00
|
|
|
|
2020-08-16 08:10:08 +03:00
|
|
|
The container also has:
|
2015-11-20 19:52:19 +03:00
|
|
|
|
2020-08-16 08:10:08 +03:00
|
|
|
- ``container.overridden`` - tuple of all overriding containers.
|
|
|
|
- ``container.reset_last_overriding()`` - reset last overriding for each provider in the container.
|
|
|
|
- ``container.reset_override()`` - reset all overriding in the container.
|
2017-02-28 23:08:52 +03:00
|
|
|
|
2020-08-16 08:10:08 +03:00
|
|
|
:py:class:`DynamicContainer` has the same functionality.
|
2017-02-28 23:08:52 +03:00
|
|
|
|
2020-10-22 19:00:46 +03:00
|
|
|
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.
|
|
|
|
|
2017-02-28 23:08:52 +03:00
|
|
|
.. disqus::
|