Files
Telegrator/Telegrator.Hosting/TelegramBotHostBuilder.cs
T

80 lines
2.9 KiB
C#
Raw Normal View History

2025-07-24 23:19:59 +04:00
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Telegram.Bot;
using Telegram.Bot.Polling;
using Telegrator.Hosting;
using Telegrator.Hosting.Components;
using Telegrator.Hosting.Configuration;
2025-07-24 23:19:59 +04:00
using Telegrator.Hosting.Providers;
using Telegrator.MadiatorCore;
#pragma warning disable IDE0001
namespace Telegrator.Hosting
{
/// <summary>
/// Represents a hosted telegram bots and services builder that helps manage configuration, logging, lifetime, and more.
/// </summary>
2025-07-24 23:19:59 +04:00
public class TelegramBotHostBuilder : ITelegramBotHostBuilder
{
private readonly HostApplicationBuilder _innerBuilder;
private readonly TelegramBotHostBuilderSettings _settings;
private readonly HostHandlersCollection _handlers;
/// <inheritdoc/>
public IHandlersCollection Handlers => _handlers;
/// <inheritdoc/>
public IServiceCollection Services => _innerBuilder.Services;
/// <inheritdoc/>
public IConfigurationManager Configuration => _innerBuilder.Configuration;
/// <inheritdoc/>
public ILoggingBuilder Logging => _innerBuilder.Logging;
/// <inheritdoc/>
public IHostEnvironment Environment => _innerBuilder.Environment;
/// <summary>
/// Initializes a new instance of the <see cref="TelegramBotHostBuilder"/> class.
/// </summary>
/// <param name="hostApplicationBuilder"></param>
/// <param name="settings"></param>
internal TelegramBotHostBuilder(HostApplicationBuilder hostApplicationBuilder, TelegramBotHostBuilderSettings? settings = null)
2025-07-24 23:19:59 +04:00
{
_innerBuilder = hostApplicationBuilder;
2025-07-24 23:19:59 +04:00
_settings = settings ?? new TelegramBotHostBuilderSettings();
_handlers = new HostHandlersCollection(Services, _settings);
_innerBuilder.Logging.ClearProviders();
Services.Configure<TelegratorOptions>(Configuration.GetSection(nameof(TelegratorOptions)));
2025-07-24 23:19:59 +04:00
Services.Configure<ReceiverOptions>(Configuration.GetSection(nameof(ReceiverOptions)));
Services.Configure<TelegramBotClientOptions>(Configuration.GetSection(nameof(TelegramBotClientOptions)), new TelegramBotClientOptionsProxy());
}
/// <summary>
/// Builds the host.
/// </summary>
/// <returns></returns>
public TelegramBotHost Build()
{
foreach (PreBuildingRoutine preBuildRoutine in _handlers.PreBuilderRoutines)
2025-07-24 23:19:59 +04:00
{
try
{
preBuildRoutine.Invoke(this);
}
catch (NotImplementedException)
{
_ = 0xBAD + 0xC0DE;
}
}
return new TelegramBotHost(_innerBuilder, _handlers);
}
}
}