Skip to content

Can't get contextmanager-style resource to work: #920

@Lacrymology

Description

@Lacrymology

Running version 4.43.0

No combination of calling the provider, or calling init_resources before or after calling the provider calls the __enter__ method. shutdown_resources doesn't work either:

In [22]: from dependency_injector import containers, providers
    ...: 
    ...: class DatabaseConnection:
    ...:     def __init__(self):
    ...:         self.connected = False
    ...: 
    ...:     def __enter__(self):
    ...:         print(f"Connecting db")
    ...:         self.connected = True
    ...:         return self
    ...: 
    ...:     def __exit__(self, exc_type, exc_val, exc_tb):
    ...:         print("Closing connection")
    ...:         self.connected = False
    ...: 
    ...: 
    ...: class Container(containers.DeclarativeContainer):
    ...: 
    ...:     config = providers.Configuration()
    ...:     db = providers.Resource(
    ...:         DatabaseConnection,
    ...:     )
    ...: 

In [23]: c = Container()

In [24]: c.db()
Out[24]: <__main__.DatabaseConnection at 0x7cb818aa2180>

In [25]: c.init_resources()

In [26]: c = Container()

In [27]: c.init_resources()

In [28]: c.db()
Out[28]: <__main__.DatabaseConnection at 0x7cb7e6116210>

In [29]: c.db().connected
Out[29]: False

In [30]: c.db.init().connected
Out[30]: False

In [31]: c = Container()

In [32]: c.init_resources()

function-type resources work fine, but I don't think they can be shutdown. Creating a contextmanager from a function with @contextlib.contextmanager doesn't work either.

Tested with the latest version, can't get that to work either

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions