Skip to content

Docs: Dependency Injection #2173

Answered by Alc-Alc
filipvh asked this question in Q&A
Discussion options

You must be logged in to vote

Heya @filipvh, from what I understand you want a variant of what is shown here, I have slightly modified that example to use classes. Hope this solves what you are after. Worth noting is that, you should have the class you wish to inject be a parameter to __init__, then later use that where you want.

from litestar import Litestar, get
from random import randint


class FirstDependency:
    def do_something(self) -> int:
        return randint(1, 10)


class SecondDependency:
    def __init__(self, first_dependency: FirstDependency):
        self.first_dependency: FirstDependency = first_dependency

    def do_something_else(self) -> bool:
        return self.first_dependency.do_something() %

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by JacobCoffee
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
Documentation 📚 This is related to documentation
2 participants
Converted from issue

This discussion was converted from issue #2171 on August 17, 2023 01:38.