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

TypeError: object NoneType can't be used in 'await' expression for init_resources() of nested container

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

Hi! It my first try in dependency injection. I have container of Database with asyncpg.Pool as resource:

async def create_pool() -> asyncpg.Pool:
    pool = await asyncpg.create_pool(
        user="postgres",
        password="SomePassword",
        database="postgres"
    )

    return pool


class Container(containers.DynamicContainer):
    pool = providers.Resource(create_pool)

    db_factory = providers.Factory(Database, pool)

And I have root container:

class Container(containers.DeclarativeContainer):
    database_container = providers.Container(DbContainer)

Entry point:

def create_app() -> FastAPI:
    container = Container()
    container.wire(["__main__"])

    db_container = container.database_container

    app_instance = FastAPI()

    @app_instance.on_event("startup")
    async def startup():
        await db_container.init_resources()  <--- here is error
        
        database = db_container.db_factory()
        
        await database.create()

    return app_instance


app = create_app()


if __name__ == '__main__':
    os.system("uvicorn main:app --lifespan on")

When I try to run it I get following error:

await db_container.init_resources()
TypeError: object NoneType can't be used in 'await' expression

What am I doing wrong? And should I use this structure of containers or is there a better option?

OlehDziuba avatar Jan 08 '23 18:01 OlehDziuba