Reset container singletonsΒΆ

To reset all container singletons use method .reset_singletons().

from dependency_injector import containers, providers


class Container(containers.DeclarativeContainer):

    service1 = providers.Singleton(object)
    service2 = providers.Singleton(object)


if __name__ == '__main__':
    container = Container()

    service1 = container.service1()
    service2 = container.service2()

    container.reset_singletons()

    assert service1 is not container.service1()
    assert service2 is not container.service2()

Method .reset_singletons() also resets singletons in sub-containers: providers.Container and providers.DependenciesContainer.

from dependency_injector import containers, providers


class SubContainer(containers.DeclarativeContainer):

    service = providers.Singleton(object)


class Container(containers.DeclarativeContainer):

    service = providers.Singleton(object)
    sub = providers.Container(SubContainer)


if __name__ == '__main__':
    container = Container()

    service1 = container.service()
    service2 = container.sub().service()

    container.reset_singletons()

    assert service1 is not container.service()
    assert service2 is not container.sub().service()

You can use .reset_singletons() method with a context manager. Singletons will be reset on both entering and exiting a context.

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

See also: Singleton provider.