Skip to content

Asynccontextmanager provider does not return the instance of the class #112

Open
@stefanocardarelli

Description

@stefanocardarelli

Hello,

I am trying to bind an interface to an async provider.

In the script I pasted below you will notice it is not strictly necessary to have an async provider, however I am trying to evaluate this library for a project that requires some async functions to instantiate connections, and I'm doing a sort of proof of concept.

I initially tried using inject.attr(IService) on the class attributes but an error suggested me to use autoparams instead off attr for async contexts:

Image

So I switched to a custom constructor for the class to use autoparams on, but I get the following error

Image

It seems the provider does not return the instance I need but the _AsyncGeneratorContextManager itself

This is the current script, it should run as is

import asyncio
from contextlib import asynccontextmanager
from typing import Protocol, Self, runtime_checkable

import inject
from inject import Binder
from pydantic import BaseModel


@runtime_checkable
class IService(Protocol):
    async def do_stuff(self) -> None: ...


class PrintService:
    async def do_stuff(self) -> None:
        print("PrintService is doing stuff")


class MyClass(BaseModel):
    service: IService

    model_config = {"arbitrary_types_allowed": True}

    async def execute(self) -> None:
        await self.service.do_stuff()

    @classmethod
    @inject.autoparams()
    def new(cls, service: IService) -> Self:
        return cls(service=service)


@asynccontextmanager
async def provide_print_service():
    yield PrintService()


def bootstrapper(binder: Binder):
    binder.bind_to_provider(IService, provide_print_service)


inject.configure(bootstrapper)


async def main():
    my_class = MyClass.new()
    await my_class.execute()


asyncio.run(main())

This is the list of the dependencies you need to run this script

  • pydantic 2.10.4
  • inject 5.2.1

Maybe I'm doing something wrong on my side, can you help me out?
If i need to provide more information please ask.

Thanks in advance!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions