using System.Diagnostics.CodeAnalysis; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenHarbor.JwtTokenManager.Abstractions; namespace OpenHarbor.JwtTokenManager; public static class ServiceCollectionExtensions { [RequiresDynamicCode("Not AoT safe signature. Will add one in the future.")] public static IServiceCollection AddJwtTokenManager( this IServiceCollection services, IConfiguration configuration, string sectionName, Action? configureBuilderOptions = null) { if (configuration == null) throw new ArgumentNullException(nameof(configuration)); if (string.IsNullOrWhiteSpace(sectionName)) throw new ArgumentException("Section name must be provided.", nameof(sectionName)); services.Configure(configuration.GetSection(sectionName)); // Apply the builder options var builderOptions = new JwtTokenManagerBuilderOptions(); configureBuilderOptions?.Invoke(builderOptions); // Register the service services.AddSingleton(provider => { var optionsMonitor = provider.GetRequiredService>(); var options = optionsMonitor.Get(Options.DefaultName); // Apply additional configuration builderOptions.AdditionalConfiguration?.Invoke(options); // Configure cache options var cacheOptions = new JwtTokenManagerCacheOptions(); builderOptions.CacheOptions?.Invoke(cacheOptions); var memoryCache = builderOptions.CacheFactory?.Invoke(provider) ?? provider.GetService(); var httpClientFactory = provider.GetRequiredService(); var logger = provider.GetService>(); return new JwtTokenManagerService(options, httpClientFactory, logger, memoryCache, cacheOptions); }); return services; } }