diff --git a/docs/containers/reset_singletons.rst b/docs/containers/reset_singletons.rst index 7d315099..64105369 100644 --- a/docs/containers/reset_singletons.rst +++ b/docs/containers/reset_singletons.rst @@ -18,6 +18,14 @@ Method ``.reset_singletons()`` also resets singletons in sub-containers: ``provi :lines: 3- :emphasize-lines: 21 +You can use ``.reset_singletons()`` method with a context manager. Singletons will be reset on +both entering and exiting a context. + +.. literalinclude:: ../../examples/containers/reset_singletons_with.py + :language: python + :lines: 3- + :emphasize-lines: 14-15 + See also: :ref:`singleton-provider`. .. disqus:: diff --git a/examples/containers/reset_singletons_with.py b/examples/containers/reset_singletons_with.py new file mode 100644 index 00000000..6f919cb8 --- /dev/null +++ b/examples/containers/reset_singletons_with.py @@ -0,0 +1,23 @@ +"""Container reset singletons context manager example.""" + +from dependency_injector import containers, providers + + +class Container(containers.DeclarativeContainer): + + service = providers.Singleton(object) + + +if __name__ == '__main__': + container = Container() + + service1 = container.service() + + with container.reset_singletons(): + service2 = container.service() + + service3 = container.service() + + assert service1 is not service2 + assert service2 is not service3 + assert service3 is not service1