using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Telegrator.Core; namespace Telegrator.Hosting { /// /// Represents a hosted telegram bot /// public class TelegramBotHost : IHost, ITelegratorBot { private readonly IHost _innerHost; private readonly IUpdateRouter _updateRouter; private readonly ILogger _logger; private bool _disposed; /// public IServiceProvider Services => _innerHost.Services; /// public IUpdateRouter UpdateRouter => _updateRouter; /// /// This application's logger /// public ILogger Logger => _logger; /// /// Initializes a new instance of the class. /// /// The proxied instance of host builder. public TelegramBotHost(HostApplicationBuilder hostApplicationBuilder) { // Registering this host in services for easy access hostApplicationBuilder.Services.AddSingleton(this); // Building proxy hoster _innerHost = hostApplicationBuilder.Build(); // Reruesting services for this host _updateRouter = Services.GetRequiredService(); _logger = Services.GetRequiredService>(); } /// /// Creates new with default configuration, services and long-polling update receiving scheme /// /// public static TelegramBotHostBuilder CreateBuilder() { HostApplicationBuilder innerBuilder = new HostApplicationBuilder(settings: null); TelegramBotHostBuilder builder = new TelegramBotHostBuilder(innerBuilder, null); return builder; } /// /// Creates new with default services and long-polling update receiving scheme /// /// public static TelegramBotHostBuilder CreateBuilder(HostApplicationBuilderSettings? settings) { HostApplicationBuilder innerBuilder = new HostApplicationBuilder(settings); TelegramBotHostBuilder builder = new TelegramBotHostBuilder(innerBuilder, settings); return builder; } /// /// Creates new EMPTY WITHOUT any services or update receiving schemes /// /// public static TelegramBotHostBuilder CreateEmptyBuilder() { HostApplicationBuilder innerBuilder = Host.CreateEmptyApplicationBuilder(null); return new TelegramBotHostBuilder(innerBuilder, null); } /// /// Creates new EMPTY WITHOUT any services or update receiving schemes /// /// public static TelegramBotHostBuilder CreateEmptyBuilder(HostApplicationBuilderSettings? settings) { HostApplicationBuilder innerBuilder = Host.CreateEmptyApplicationBuilder(null); return new TelegramBotHostBuilder(innerBuilder, settings); } /// public async Task StartAsync(CancellationToken cancellationToken = default) { await _innerHost.StartAsync(cancellationToken); } /// public async Task StopAsync(CancellationToken cancellationToken = default) { await _innerHost.StopAsync(cancellationToken); } /// /// Disposes the host. /// public void Dispose() { if (_disposed) return; _innerHost.Dispose(); GC.SuppressFinalize(this); _disposed = true; } } }