Skip to content

Dependencies

aiopayme has a built-in dependency injection system inspired by aiogram. You can inject any object into your handlers just by adding it as a type-annotated argument.

How it works

Dependencies are registered on the Payme instance via provide() and set_context(). When a handler is called, aiopayme resolves the arguments automatically by their type.

Registering Dependencies

set_context

Use set_context for single instances — objects that are created once and reused:

from aiogram import Bot

bot = Bot(token="your_token")
payme.set_context(bot=bot)

provide

Use provide for factory dependencies — objects that are created per request, like a database session:

from sqlalchemy.ext.asyncio import AsyncSession
from app.deps import SessionLocal

payme.provide(AsyncSession, SessionLocal)

deps.py Example

# deps.py
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
from aiopayme import Payme

engine = create_async_engine("sqlite+aiosqlite:///./db.sqlite3")
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)

def get_payme() -> Payme:
    return Payme(
        merchant_id="your_merchant_id",
        secret_key="your_secret_key",
        sandbox=True,
    )

Then in your main.py:

from app.deps import get_payme, SessionLocal
from sqlalchemy.ext.asyncio import AsyncSession

payme = get_payme()
payme.provide(AsyncSession, SessionLocal)

SessionLocal is a callable that returns an AsyncSession — aiopayme will call it automatically for each incoming request.

Using Dependencies in Handlers

Once registered, just add the dependency as a type-annotated argument to your handler:

from aiogram import Bot
from sqlalchemy.ext.asyncio import AsyncSession
from aiopayme.types import PerformTransactionCtx

@router.perform_transaction()
async def perform_transaction(
    ctx: PerformTransactionCtx,
    db: AsyncSession,
    bot: Bot,
):
    tx = await PaymeService(db).perform_transaction(ctx)
    await bot.send_message(
        chat_id=ctx.account.chat_id,
        text="Your payment has been confirmed.",
    )
    return tx

aiopayme resolves db and bot automatically — no manual wiring needed.

Full Setup Example

from fastapi import FastAPI
from aiogram import Bot
from sqlalchemy.ext.asyncio import AsyncSession

from aiopayme import Payme, Dispatcher
from app.deps import SessionLocal, get_payme()

app = FastAPI()
bot = Bot(token="your_token")

payme = get_payme()

dp = Dispatcher()
dp.include_router(router)

payme.setup(dp)
payme.set_context(bot=bot)
payme.provide(AsyncSession, SessionLocal)