Skip to main content
When your project references Microsoft.Extensions.Hosting.Abstractions, the PolyBot source generator emits PolyBotPollingHostedService and the AddPolyBotHostedPolling extension method. This integration lets you run a PolyBot bot as an IHostedService inside any IHost-based application, alongside logging, configuration, and other hosted services.
The hosted-polling integration is generated only when Microsoft.Extensions.Hosting.Abstractions is referenced in your project. If you are using PolyBotClient in a console application without the hosting package, see Standalone Polling instead.

What the generated service does

PolyBotPollingHostedService implements IHostedService and manages the full polling lifecycle:

Registration

Call AddPolyBotHostedPolling on your IServiceCollection. The method registers a fallback ITelegramBotClient built from the registered PolyBotOptions.BotToken, calls AddPolyBotRouter(), builds a ReceiverOptions from the optional delegate, and adds PolyBotPollingHostedService as IHostedService.
PolyBotOptions must be registered as a singleton before calling AddPolyBotHostedPolling. The hosted service resolves it from the DI container on construction, and the fallback ITelegramBotClient is built from its BotToken. Register it yourself before calling AddPolyBotHostedPolling.
Registering your own ITelegramBotClient before AddPolyBotHostedPolling takes precedence over the fallback — this is how you plug in PolyTests for integration testing or a custom client.
The ReceiverOptions delegate is optional — omitting it uses defaults (no update drop, all update types, no limit override):

DI wiring

The typical registration order for a generic-host bot:
1

Register PolyBotOptions

Register your options instance as a singleton. This is the single source of truth for the bot token, username, and polling settings.
2

Register application services

Add your own services — handlers’ dependencies are resolved from the same container.
3

Call AddPolyBotHostedPolling

This registers the Telegram client (from PolyBotOptions.BotToken), the generated router (IUpdateHandler) — including IBotFatherSync, synced at startup — and the hosted polling service.

Complete Program.cs example

A minimal IHost application that reads configuration from appsettings.json and polls until the process is stopped:

Using PolyTests with the hosted service

For integration testing, swap ITelegramBotClient for PolyTests before calling AddPolyBotHostedPolling. Updates injected with EnqueueUpdate are delivered to the polling loop exactly as real Telegram updates would be:
See PolyTests for the full API surface of the in-memory bot client, including SentRequests assertions and long-poll semantics.