Skip to content

How to inject a dependency in a Controller class? #3717

Answered by sinisaos
l3t2st1r asked this question in Q&A
Discussion options

You must be logged in to vote

@l3t2st1r I'm sorry if I didn't understand your request well (I'm also not a Litestar expert and I don't know if this is a good approach), but you can use super() to use the argument of the parent controller in the child controllers. Something like this

Example code
from litestar import Litestar, Controller, get
from litestar.di import Provide


async def str_fn() -> str:
    return "Dependency example"


class BaseController(Controller):
    path = "/"
    dependencies = {"db_handler": Provide(str_fn)}

    @get("parent")
    async def parent_get(self) -> str:
        return "Parent controller"


class ChildController(BaseController):
    path = "/child/"

    def __init__(self, owner):…

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@l3t2st1r
Comment options

@sinisaos
Comment options

Answer selected by l3t2st1r
@provinzkraut
Comment options

@l3t2st1r
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants