mtcute/docs/guide/dispatcher/di.md
alina sireneva 690948b8b1
All checks were successful
Build and deploy typedoc / build (push) Successful in 5m15s
chore: moved docs inside the main repo
Co-authored-by: Kamilla 'ova <me@kamillaova.dev>
Co-authored-by: Alina Chebakova <chebakov05@gmail.com>
Co-authored-by: Kravets <57632712+kravetsone@users.noreply.github.com>
Co-authored-by: starkow <hello@starkow.dev>
Co-authored-by: sireneva <150665887+sireneva@users.noreply.github.com>
2025-01-17 08:50:35 +03:00

43 lines
No EOL
1.1 KiB
Markdown

# Dependency Injection
When scaling up your bot to multiple files, you may find it useful to inject dependencies
into the children dispatchers instead of having to pass them around manually.
`@mtcute/dispatcher` provides a simple service locator that you can use to inject dependencies:
```ts
// for typescript, you need to declare the dependencies
declare module '@mtcute/dispatcher' {
interface DispatcherDependencies {
db: Database
}
}
// create a root dispatcher
const dp = Dispatcher.for(tg)
// inject the database
dp.inject('db', new Database())
// or
dp.inject({ db: new Database() })
// and then add a child dispatcher
import { childDispatcher } from './file2'
dp.addChild(childDispatcher)
// file2.ts
const dp = Dispatcher.child()
dp.onNewMessage(async (ctx) => {
// the dependencies are available in dp.deps
const db = dp.deps.db
await db.saveMessage(ctx.message)
})
export const childDispatcher = dp
```
::: info
You can only inject dependencies into the root dispatcher (the one created with `Dispatcher.for`),
and they will be available in *all* children dispatchers.
:::