From 441cc66427c244e1a4a2e2239b465cdb7668b255 Mon Sep 17 00:00:00 2001 From: Roman Mogylatov Date: Thu, 3 Sep 2020 17:57:26 -0400 Subject: [PATCH] Improve singleton provider docs --- docs/providers/singleton.rst | 7 ++++++ .../singleton_multiple_containers.py | 24 +++++++++++++++++++ examples/providers/singleton_resetting.py | 4 ++-- 3 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 examples/providers/singleton_multiple_containers.py diff --git a/docs/providers/singleton.rst b/docs/providers/singleton.rst index c42b6a3e..6624777f 100644 --- a/docs/providers/singleton.rst +++ b/docs/providers/singleton.rst @@ -32,6 +32,13 @@ factories: - :ref:`factory-specialize-provided-type` - :ref:`abstract-factory` +``Singleton`` provider scope is tied to the container. Two different containers will provider +two different singleton objects: + +.. literalinclude:: ../../examples/providers/singleton_multiple_containers.py + :language: python + :lines: 3- + Resetting memorized object -------------------------- diff --git a/examples/providers/singleton_multiple_containers.py b/examples/providers/singleton_multiple_containers.py new file mode 100644 index 00000000..7b5e4fab --- /dev/null +++ b/examples/providers/singleton_multiple_containers.py @@ -0,0 +1,24 @@ +"""`Singleton` provider resetting example.""" + +from dependency_injector import containers, providers + + +class UserService: + ... + + +class Container(containers.DeclarativeContainer): + + user_service_provider = providers.Singleton(UserService) + + +if __name__ == '__main__': + container1 = Container() + user_service1 = container1.user_service_provider() + assert user_service1 is container1.user_service_provider() + + container2 = Container() + user_service2 = container2.user_service_provider() + assert user_service2 is container2.user_service_provider() + + assert user_service1 is not user_service2 diff --git a/examples/providers/singleton_resetting.py b/examples/providers/singleton_resetting.py index 7188744b..48e3cadf 100644 --- a/examples/providers/singleton_resetting.py +++ b/examples/providers/singleton_resetting.py @@ -19,5 +19,5 @@ if __name__ == '__main__': container.user_service_provider.reset() - users_service2 = container.user_service_provider() - assert users_service2 is not user_service1 + user_service2 = container.user_service_provider() + assert user_service2 is not user_service1