Skip to content

Using fundi for Dependency Injection in Event Handlers #142

@kuyugama

Description

@kuyugama

Checklist

  • I believe the idea is awesome and would benefit the framework
  • I have searched in the issue tracker for similar requests, including closed ones

Description

Dependency injection is a powerful and convenient design pattern — and with FunDI, integrating it becomes effortless.

Since this library supports Python up to 3.9, the best way to include it as an optional dependency is like so:

pip install pyrofork[fundi]

Proposed Integration Example

from fundi import from_, FromType
from pyrogram import Client, filters
from pyrogram.types import Message


app = Client("my_account")


def require_user_mention(message: FromType[Message]) -> str:
    user = message.from_user

    if user.username is not None:
        return f"{user.mention}(@{user.username}|{user.id})"
    return f"{user.mention}({user.id})"


@app.on_message(filters.private)
async def hello(
    message: FromType[Message],
    mention: str = from_(require_user_mention),
):
    await message.reply(f"Hello, {mention}!")

🛠 How It Works

  • The mention argument is automatically injected via from_(), which tells FunDI to resolve it using require_user_mention.
  • FromType[Message] is a type hint that marks the message as an injectable Pyrogram context.
  • require_user_mention is a plain function (sync or async) that accepts Message and returns a formatted string.

This approach keeps your handlers clean, modular, and readable.
FunDI handles the wiring — you just write logic.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions