diff --git a/OpenHarbor.JwtTokenManager/ServiceCollectionExtensions.cs b/OpenHarbor.JwtTokenManager/ServiceCollectionExtensions.cs index 611e9a9..9185392 100644 --- a/OpenHarbor.JwtTokenManager/ServiceCollectionExtensions.cs +++ b/OpenHarbor.JwtTokenManager/ServiceCollectionExtensions.cs @@ -10,34 +10,35 @@ 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, - Action? configureBuilderOptions = null) + string? name = null, + 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 + name ??= sectionName; + + services.Configure(name, configuration.GetSection(sectionName)); + var builderOptions = new JwtTokenManagerBuilderOptions(); configureBuilderOptions?.Invoke(builderOptions); - // Register the service - services.AddSingleton(provider => + services.AddKeyedSingleton(name, (provider, key) => { var optionsMonitor = provider.GetRequiredService>(); - var options = optionsMonitor.Get(Options.DefaultName); + var options = optionsMonitor.Get(name); - // Apply additional configuration builderOptions.AdditionalConfiguration?.Invoke(options); - // Configure cache options var cacheOptions = new JwtTokenManagerCacheOptions(); builderOptions.CacheOptions?.Invoke(cacheOptions); @@ -48,6 +49,24 @@ public static class ServiceCollectionExtensions return new JwtTokenManagerService(options, httpClientFactory, logger, memoryCache, cacheOptions); }); + if (!_defaultRegistered) + { + services.AddSingleton(sp => + sp.GetRequiredKeyedService(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? configureBuilderOptions = null) + { + return AddJwtTokenManager(services, configuration, sectionName, null, configureBuilderOptions); + } }