dotnet-jwt-token-manager/OpenHarbor.JwtTokenManager/ServiceCollectionExtensions.cs

53 lines
2.0 KiB
C#
Raw Normal View History

2024-12-20 01:50:06 -05:00
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
{
public static IServiceCollection AddJwtTokenManager(
this IServiceCollection services,
IConfiguration configuration,
string sectionName,
Action<JwtTokenManagerBuilderOptions>? configureBuilderOptions = null)
{
if (configuration == null)
throw new ArgumentNullException(nameof(configuration));
if (string.IsNullOrWhiteSpace(sectionName))
throw new ArgumentException("Section name must be provided.", nameof(sectionName));
// Configure JwtTokenManagerOptions from the section
services.Configure<JwtTokenManagerOptions>(configuration.GetSection(sectionName));
// Apply the builder options
var builderOptions = new JwtTokenManagerBuilderOptions();
configureBuilderOptions?.Invoke(builderOptions);
// Register the service
services.AddSingleton<IJwtTokenManagerService>(provider =>
{
var optionsMonitor = provider.GetRequiredService<Microsoft.Extensions.Options.IOptionsMonitor<JwtTokenManagerOptions>>();
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<IMemoryCache>();
var httpClientFactory = provider.GetRequiredService<IHttpClientFactory>();
var logger = provider.GetService<ILogger<JwtTokenManagerService>>();
return new JwtTokenManagerService(options, httpClientFactory, logger, memoryCache, cacheOptions);
});
return services;
}
}