dotnet-jwt-token-manager/OpenHarbor.JwtTokenManager/ServiceCollectionExtensions.cs
Mathias Beaulieu-Duncan 6dccfa0bca
All checks were successful
Publish NuGets / build (release) Successful in 21s
added keyed singleton for muilti instances
2025-08-30 15:39:25 -04:00

73 lines
2.6 KiB
C#

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
{
private static bool _defaultRegistered = false;
[RequiresDynamicCode("Not AoT safe signature. Will add one in the future.")]
public static IServiceCollection AddJwtTokenManager(
this IServiceCollection services,
IConfiguration configuration,
string sectionName,
string? name = null,
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));
name ??= sectionName;
services.Configure<JwtTokenManagerOptions>(name, configuration.GetSection(sectionName));
var builderOptions = new JwtTokenManagerBuilderOptions();
configureBuilderOptions?.Invoke(builderOptions);
services.AddKeyedSingleton<IJwtTokenManagerService>(name, (provider, key) =>
{
var optionsMonitor = provider.GetRequiredService<IOptionsMonitor<JwtTokenManagerOptions>>();
var options = optionsMonitor.Get(name);
builderOptions.AdditionalConfiguration?.Invoke(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);
});
if (!_defaultRegistered)
{
services.AddSingleton<IJwtTokenManagerService>(sp =>
sp.GetRequiredKeyedService<IJwtTokenManagerService>(name));
_defaultRegistered = true;
}
return services;
}
[RequiresDynamicCode("Not AoT safe signature. Will add one in the future.")]
public static IServiceCollection AddJwtTokenManager(
this IServiceCollection services,
IConfiguration configuration,
string sectionName,
Action<JwtTokenManagerBuilderOptions>? configureBuilderOptions = null)
{
return AddJwtTokenManager(services, configuration, sectionName, null, configureBuilderOptions);
}
}