Skip to content

Commit 4f4730a

Browse files
committed
fix(telegram): support using inject decorator on BaseHandler.handle
1 parent ba77fe6 commit 4f4730a

File tree

3 files changed

+22
-4
lines changed

3 files changed

+22
-4
lines changed

aioinject/ext/aiogram.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from typing import Any
44

55
from aiogram import BaseMiddleware, Router
6+
from aiogram.handlers import BaseHandler
67
from aiogram.types import TelegramObject
78

89
import aioinject
@@ -20,16 +21,21 @@ class _ContextGetter:
2021
def __init__(self, *, remove_from_args: bool) -> None:
2122
self.remove_from_args = remove_from_args
2223

23-
def __call__(
24-
self, args: tuple[Any], kwargs: dict[str, Any]
24+
def __call__( # noqa: C901
25+
self,
26+
args: tuple[Any],
27+
kwargs: dict[str, Any],
2528
) -> aioinject.Context:
2629
if _ARG_NAME in kwargs: # pragma: no cover
2730
if self.remove_from_args:
2831
return kwargs.pop(_ARG_NAME)
2932
return kwargs[_ARG_NAME]
3033

3134
# Try to find a dict-like looking object (in case it's a middleware)
32-
for arg in args:
35+
for arg_pos, arg in enumerate(args):
36+
# BaseHandler.handle is being called
37+
if arg_pos == 0 and isinstance(arg, BaseHandler):
38+
arg = arg.data # noqa: PLW2901
3339
if not isinstance(arg, dict):
3440
continue
3541
if _ARG_NAME in arg:

tests/integrations/test_aiogram.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
import pytest
55
from aiogram import BaseMiddleware, Router
6+
from aiogram.handlers import MessageHandler
67
from aiogram.types import TelegramObject
78

89
import aioinject
@@ -36,6 +37,17 @@ async def handler(
3637
await middleware(handler=handler, event=event_, data=data_) # type: ignore[arg-type]
3738

3839

40+
async def test_class_handler(container: Container) -> None:
41+
class MyHandler(MessageHandler):
42+
@inject
43+
async def handle(self, number: Injected[int] = INJECTED) -> Any:
44+
return number
45+
46+
async with container.context() as ctx:
47+
handler = MyHandler(object(), aioinject_context=ctx) # type: ignore[arg-type]
48+
assert await handler.handle() is await container.root.resolve(int)
49+
50+
3951
async def test_can_inject_into_middleware(container: Container) -> None:
4052
class CustomMiddleware(BaseMiddleware):
4153
@inject

uv.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)