mirror of
https://github.com/ets-labs/python-dependency-injector.git
synced 2025-07-06 05:13:13 +03:00
Add docs
This commit is contained in:
parent
39144b34a2
commit
7d4172c144
|
@ -22,6 +22,7 @@ Containers module API docs - :py:mod:`dependency_injector.containers`.
|
||||||
declarative
|
declarative
|
||||||
dynamic
|
dynamic
|
||||||
specialization
|
specialization
|
||||||
|
inject_self
|
||||||
overriding
|
overriding
|
||||||
reset_singletons
|
reset_singletons
|
||||||
traversal
|
traversal
|
||||||
|
|
20
docs/containers/inject_self.rst
Normal file
20
docs/containers/inject_self.rst
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
Injecting container "self"
|
||||||
|
==========================
|
||||||
|
|
||||||
|
You can inject container "self" into container providers.
|
||||||
|
|
||||||
|
.. literalinclude:: ../../examples/containers/inject_self.py
|
||||||
|
:language: python
|
||||||
|
:lines: 3-
|
||||||
|
:emphasize-lines: 20, 26
|
||||||
|
|
||||||
|
To inject container "self" you need to define ``Self`` provider. Container can have only one ``Self`` provider.
|
||||||
|
|
||||||
|
Usually you will use name ``__self__``.
|
||||||
|
You can also use different name. When you use different name container will also reference
|
||||||
|
defined ``Self`` provider in ``.__self__`` attribute.
|
||||||
|
|
||||||
|
Provider ``Self`` is not listed in container ``.providers`` attributes.
|
||||||
|
|
||||||
|
.. disqus::
|
||||||
|
|
36
examples/containers/inject_self.py
Normal file
36
examples/containers/inject_self.py
Normal file
|
@ -0,0 +1,36 @@
|
||||||
|
"""Container injecting ``self`` example."""
|
||||||
|
|
||||||
|
from dependency_injector import containers, providers
|
||||||
|
|
||||||
|
|
||||||
|
class Service:
|
||||||
|
def __init__(self, name: str):
|
||||||
|
self.name = name
|
||||||
|
|
||||||
|
|
||||||
|
class ServiceDispatcher:
|
||||||
|
def __init__(self, container: containers.Container):
|
||||||
|
self.container = container
|
||||||
|
|
||||||
|
def get_services(self):
|
||||||
|
for provider in self.container.traverse(types=[providers.Factory]):
|
||||||
|
yield provider()
|
||||||
|
|
||||||
|
|
||||||
|
class Container(containers.DeclarativeContainer):
|
||||||
|
|
||||||
|
__self__ = providers.Self()
|
||||||
|
|
||||||
|
service1 = providers.Factory(Service, name='Service 1')
|
||||||
|
service2 = providers.Factory(Service, name='Service 2')
|
||||||
|
service3 = providers.Factory(Service, name='Service 3')
|
||||||
|
|
||||||
|
dispatcher = providers.Singleton(ServiceDispatcher, __self__)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
container = Container()
|
||||||
|
|
||||||
|
dispatcher = container.dispatcher()
|
||||||
|
for service in dispatcher.get_services():
|
||||||
|
print(service.name)
|
Loading…
Reference in New Issue
Block a user