ets-labs / python-dependency-injector

Dependency injection framework for Python
https://python-dependency-injector.ets-labs.org/
BSD 3-Clause "New" or "Revised" License
3.99k stars 305 forks source link

recursive_wire #817

Open lagunovartur opened 2 months ago

lagunovartur commented 2 months ago

Приветствую, хотел поинтересоваться почему в библиотеке нет рекурсивного связывания на подобие такого, это позволяет делать инъекции не от корня, а от ближайшего родителя:

Например: Так: @router.get("/test") @inject async def get_list(s3_manager = Depends(Provide[S3Container.manager])): pass

Вместо: @router.get("/test") @inject async def get_list(s3_client = Depends(Provide[AppContainer.infra.s3.manager])): pass

Рекурсивное связывание:

def recursive_wire(container, *args, **kwargs):

    container.wire(*args, **kwargs)

    for attr_name in dir(container):
        if attr_name.startswith('_') or attr_name == 'parent':
            continue
        attr = getattr(container, attr_name, None)
        if isinstance(attr, providers.Container):
            sub_container = attr() 
            recursive_wire(sub_container, *args, **kwargs)
LeOndaz commented 1 month ago

Translation

Hello,

I would like to inquire about the absence of recursive binding in the library, similar to the following. This feature allows for dependency injection from the nearest parent, rather than from the root.

For example:

@router.get("/test")
@Inject
async def get_list(s3_manager = Depends(Provide[S3Container.manager])):
    pass

Instead of:

@router.get("/test")
@Inject
async def get_list(s3_client = Depends(Provide[AppContainer.infra.s3.manager])):
    pass

Recursive binding:

def recursive_wire(container, *args, **kwargs):

    container.wire(*args, **kwargs)

    for attr_name in dir(container):
        if attr_name.startswith('_') or attr_name == 'parent':
            continue
        attr = getattr(container, attr_name, None)
        if isinstance(attr, providers.Container):
            sub_container = attr() 
            recursive_wire(sub_container, *args, **kwargs)