2025-07-24 23:19:59 +04:00
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
using Microsoft.Extensions.Options;
|
2026-03-06 23:19:24 +04:00
|
|
|
using Telegrator.Core;
|
|
|
|
|
using Telegrator.Core.Descriptors;
|
|
|
|
|
using Telegrator.Core.Handlers;
|
2025-07-24 23:19:59 +04:00
|
|
|
|
2026-03-06 23:19:24 +04:00
|
|
|
namespace Telegrator.Providers
|
2025-07-24 23:19:59 +04:00
|
|
|
{
|
2025-07-26 00:01:46 +04:00
|
|
|
/// <inheritdoc/>
|
2025-07-24 23:19:59 +04:00
|
|
|
public class HostHandlersProvider : HandlersProvider
|
|
|
|
|
{
|
|
|
|
|
private readonly IServiceProvider Services;
|
|
|
|
|
private readonly ILogger<HostHandlersProvider> Logger;
|
|
|
|
|
|
2025-07-26 00:01:46 +04:00
|
|
|
/// <inheritdoc/>
|
|
|
|
|
public HostHandlersProvider(
|
|
|
|
|
IHandlersCollection handlers,
|
2025-07-28 20:35:48 +04:00
|
|
|
IOptions<TelegratorOptions> options,
|
2025-07-26 00:01:46 +04:00
|
|
|
IServiceProvider serviceProvider,
|
2025-07-27 14:19:40 +04:00
|
|
|
ILogger<HostHandlersProvider> logger) : base(handlers, options.Value)
|
2025-07-24 23:19:59 +04:00
|
|
|
{
|
|
|
|
|
Services = serviceProvider;
|
|
|
|
|
Logger = logger;
|
|
|
|
|
}
|
|
|
|
|
|
2025-07-26 00:01:46 +04:00
|
|
|
/// <inheritdoc/>
|
2025-07-24 23:19:59 +04:00
|
|
|
public override UpdateHandlerBase GetHandlerInstance(HandlerDescriptor descriptor, CancellationToken cancellationToken = default)
|
|
|
|
|
{
|
|
|
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
|
|
|
IServiceScope scope = Services.CreateScope();
|
2025-07-27 14:19:40 +04:00
|
|
|
|
2025-07-24 23:19:59 +04:00
|
|
|
object handlerInstance = descriptor.ServiceKey == null
|
|
|
|
|
? scope.ServiceProvider.GetRequiredService(descriptor.HandlerType)
|
|
|
|
|
: scope.ServiceProvider.GetRequiredKeyedService(descriptor.HandlerType, descriptor.ServiceKey);
|
|
|
|
|
|
|
|
|
|
if (handlerInstance is not UpdateHandlerBase updateHandler)
|
2025-07-27 14:19:40 +04:00
|
|
|
throw new InvalidOperationException("Failed to resolve " + descriptor.HandlerType + " as UpdateHandlerBase");
|
2025-07-24 23:19:59 +04:00
|
|
|
|
2025-07-28 03:53:13 +04:00
|
|
|
descriptor.LazyInitialization?.Invoke(updateHandler);
|
2025-07-24 23:19:59 +04:00
|
|
|
updateHandler.LifetimeToken.OnLifetimeEnded += _ => scope.Dispose();
|
|
|
|
|
return updateHandler;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|