python-dependency-injector icon indicating copy to clipboard operation
python-dependency-injector copied to clipboard

Resources aren't being treated like singletons

Open cpvandehey opened this issue 2 years ago • 1 comments
trafficstars

Im witnessing the init method run several times on my resources.Resource class.

Heres my setup: dependency_containers.py

class MyResource(resources.Resource):
    def init(self):
        print("initialized")
        return MyResourceClass()
    ...
...

class SomeOtherResource(containers.DeclarativeContainer):
    my_resource = providers.Dependency()  # depends on MyResourceClass type
    ...
...

class ApplicationContainer(containers.DeclarativeContainer):
    """
    The primary purpose of this container is to wire everything together in one place.
    """
    # definition
    my_resource = providers.Resource(MyResource)

    # embedded usage in SomeOtherResource
    some_other_resource = providers.Container(
        SomeOtherResource,
        my_resource=my_resource,
    )

Finally in my main method:

application_container = dependency_containers.ApplicationContainer()
application_container.init_resources()
application_container.wire(modules=module_names, packages=packages)

When I set a breakpoint in the init method of MyResource, I see the debugger hits it twice! The first time is when the code hits the init_resources line (expected) and the second is when I finally create/use some_other_resource. I assumed the Resource provider would behave like a singleton and only be created once.

Oddly enough, if I remove the call to application_container.init_resources() AND I create two different Containers that depend on my_resource (~= SomeOtherResource), I then see the behavior as expected. Its almost like the initialized property isn't globally tracked.

cpvandehey avatar Mar 14 '23 01:03 cpvandehey

I partially solved the issue.

Basically, I had Provide[] placeholders that were not being wired because they were being edited by functions later on. This caused the library to NOT wire these and thus create them on the fly again when the code was actually called.

cpvandehey avatar May 04 '23 18:05 cpvandehey