-
Summaryhttps://docs.litestar.dev/2/usage/dependency-injection.html I might (probably) be missing something, but I was wondering (seems to be no example) that if I inject a class into a controller. If in that class I can inject an other class? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
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 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() % 2 == 0
@get("/true-or-false")
async def true_or_false_handler(second_dependency: SecondDependency) -> str:
return (
"its true!" if second_dependency.do_something_else() else "nope, its false..."
)
app = Litestar(
debug=True,
route_handlers=[true_or_false_handler],
dependencies={
"first_dependency": FirstDependency,
"second_dependency": SecondDependency,
},
) |
Beta Was this translation helpful? Give feedback.
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.