Skip to content

Custom dependency injection mechanism #584

Closed Answered by peterschutt
ReznikovRoman asked this question in Q&A
Discussion options

You must be logged in to vote

How about something like this?

from typing import AsyncIterator

from dependency_injector import containers, providers

from starlite import Provide, Starlite, State, get


# cache.py
class Cache:
    @classmethod
    async def from_url(cls) -> "Cache":
        return cls()

    async def get(self) -> None:
        print("Value")


async def init_cache() -> AsyncIterator[Cache]:
    cache = await Cache.from_url()
    yield cache


# containers.py
class Container(containers.DeclarativeContainer):
    cache = providers.Resource(init_cache)


# controllers.py
@get("/1")
async def controller(cache: Cache) -> None:
    await cache.get()  # >>> Value


# main.py
async def get_cache(state: State) 

Replies: 7 comments 22 replies

Comment options

You must be logged in to vote
14 replies
@ReznikovRoman
Comment options

@Goldziher
Comment options

@peterschutt
Comment options

@ReznikovRoman
Comment options

@peterschutt
Comment options

Comment options

You must be logged in to vote
1 reply
@ReznikovRoman
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@ReznikovRoman
Comment options

Answer selected by Goldziher
Comment options

You must be logged in to vote
1 reply
@ReznikovRoman
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
5 replies
@peterschutt
Comment options

@ThirVondukr
Comment options

@ReznikovRoman
Comment options

@peterschutt
Comment options

@ThirVondukr
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
Question This is a question and further information is requested
4 participants
Converted from issue

This discussion was converted from issue #582 on October 13, 2022 14:29.