From cb001e1fcb1e0a26903ddf3ff62b56b946cc117a Mon Sep 17 00:00:00 2001 From: Roman Mogylatov Date: Sun, 21 Feb 2021 10:27:35 -0500 Subject: [PATCH] Add example and docs --- docs/wiring.rst | 76 ++++++++++++++++++++++++++++ examples/wiring/example_string_id.py | 27 ++++++++++ 2 files changed, 103 insertions(+) create mode 100644 examples/wiring/example_string_id.py diff --git a/docs/wiring.rst b/docs/wiring.rst index 16126de6..195f469e 100644 --- a/docs/wiring.rst +++ b/docs/wiring.rst @@ -88,6 +88,82 @@ Also you can use ``Provide`` marker to inject a container. :emphasize-lines: 16-19 :lines: 3- +Strings identifiers +------------------- + +You can use wiring with string identifiers. String identifier should match provider name in the container: + +.. literalinclude:: ../examples/wiring/example_string_id.py + :language: python + :emphasize-lines: 17 + :lines: 3- + +With string identifiers you don't need to use a container to specify an injection. + +To specify an injection from a nested container use point ``.`` as a separator: + +.. code-block:: python + + @inject + def foo(service: UserService = Provide['services.user']) -> None: + ... + +You can also use injection modifiers: + +.. code-block:: python + + from dependency_injector.wiring import ( + inject, + Provide, + as_int, + as_float, + as_, + required, + invariant, + provided, + ) + + + @inject + def foo(value: int = Provide['config.option', as_int()]) -> None: + ... + + + @inject + def foo(value: float = Provide['config.option', as_float()]) -> None: + ... + + + @inject + def foo(value: Decimal = Provide['config.option', as_(Decimal)]) -> None: + ... + + @inject + def foo(value: str = Provide['config.option', required()]) -> None: + ... + + @inject + def foo(value: int = Provide['config.option', required().as_int()]) -> None: + ... + + + @inject + def foo(value: int = Provide['config.option', invariant('config.switch')]) -> None: + ... + + @inject + def foo(value: int = Provide['service', provided().foo['bar'].call()]) -> None: + ... + + +To inject a container use special identifier ````: + +.. code-block:: python + + @inject + def foo(container: Container = Provide['']) -> None: + ... + Wiring with modules and packages -------------------------------- diff --git a/examples/wiring/example_string_id.py b/examples/wiring/example_string_id.py new file mode 100644 index 00000000..c18fb4fb --- /dev/null +++ b/examples/wiring/example_string_id.py @@ -0,0 +1,27 @@ +"""Wiring string id example.""" + +import sys + +from dependency_injector import containers, providers +from dependency_injector.wiring import inject, Provide + + +class Service: + ... + + +class Container(containers.DeclarativeContainer): + + service = providers.Factory(Service) + + +@inject +def main(service: Service = Provide['service']) -> None: + ... + + +if __name__ == '__main__': + container = Container() + container.wire(modules=[sys.modules[__name__]]) + + main()