Skip to content
Prev Previous commit
Next Next commit
Add test container with element after resource
  • Loading branch information
jazzthief committed May 23, 2023
commit 2dabfaaad3469296cf44da3ca56782ce3577a493
36 changes: 34 additions & 2 deletions tests/unit/samples/wiringstringids/resourceclosing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,24 @@
from dependency_injector.wiring import inject, Provide, Closing


class Singleton:
pass


class Service:
init_counter: int = 0
shutdown_counter: int = 0
dependency: Singleton = None

@classmethod
def reset_counter(cls):
cls.init_counter = 0
cls.shutdown_counter = 0

@classmethod
def init(cls):
def init(cls, dependency: Singleton = None):
if dependency:
cls.dependency = dependency
cls.init_counter += 1

@classmethod
Expand All @@ -37,11 +44,36 @@ def init_service():
service.shutdown()


def init_service_with_singleton(singleton: Singleton):
service = Service()
service.init(singleton)
yield service
service.shutdown()


class Container(containers.DeclarativeContainer):

service = providers.Resource(init_service)
factory_service = providers.Factory(FactoryService, service)
factory_service_kwargs = providers.Factory(FactoryService, service=service)
factory_service_kwargs = providers.Factory(
FactoryService,
service=service
)
nested_service = providers.Factory(NestedService, factory_service)


class ContainerSingleton(containers.DeclarativeContainer):
Copy link
Contributor Author

@jazzthief jazzthief May 24, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added another container to cover a case where a resource is not at the end of the dependency graph. A Singleton provider type is arbitrary - its type doesn't play any role in injections, just needed something for a Resource to depend on.


singleton = providers.Resource(Singleton)
service = providers.Resource(
init_service_with_singleton,
singleton
)
factory_service = providers.Factory(FactoryService, service)
factory_service_kwargs = providers.Factory(
FactoryService,
service=service
)
nested_service = providers.Factory(NestedService, factory_service)


Expand Down