Files
Telegrator/src/Telegrator.Hosting/Providers/HostHandlersProvider.cs
T

41 lines
1.5 KiB
C#
Raw Normal View History

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