对比新文件 |
| | |
| | | 锘縰sing Microsoft.Extensions.DependencyInjection; |
| | | using Microsoft.Extensions.Options; |
| | | using System; |
| | | using System.Collections.Generic; |
| | | using System.Linq; |
| | | using System.Text; |
| | | using System.Threading.Tasks; |
| | | |
| | | namespace WIDESEA_Core.Core |
| | | { |
| | | public static class ConfigurableOptions |
| | | { |
| | | /// <summary>娣诲姞閫夐」閰嶇疆</summary> |
| | | /// <typeparam name="TOptions">閫夐」绫诲瀷</typeparam> |
| | | /// <param name="services">鏈嶅姟闆嗗悎</param> |
| | | /// <returns>鏈嶅姟闆嗗悎</returns> |
| | | public static IServiceCollection AddConfigurableOptions<TOptions>(this IServiceCollection services) |
| | | where TOptions : class, IConfigurableOptions |
| | | { |
| | | Type optionsType = typeof(TOptions); |
| | | string path = GetConfigurationPath(optionsType); |
| | | services.Configure<TOptions>(App.Configuration.GetSection(path)); |
| | | |
| | | return services; |
| | | } |
| | | |
| | | public static IServiceCollection AddConfigurableOptions(this IServiceCollection services, Type type) |
| | | { |
| | | string path = GetConfigurationPath(type); |
| | | var config = App.Configuration.GetSection(path); |
| | | |
| | | Type iOptionsChangeTokenSource = typeof(IOptionsChangeTokenSource<>); |
| | | Type iConfigureOptions = typeof(IConfigureOptions<>); |
| | | Type configurationChangeTokenSource = typeof(ConfigurationChangeTokenSource<>); |
| | | Type namedConfigureFromConfigurationOptions = typeof(NamedConfigureFromConfigurationOptions<>); |
| | | iOptionsChangeTokenSource = iOptionsChangeTokenSource.MakeGenericType(type); |
| | | iConfigureOptions = iConfigureOptions.MakeGenericType(type); |
| | | configurationChangeTokenSource = configurationChangeTokenSource.MakeGenericType(type); |
| | | namedConfigureFromConfigurationOptions = namedConfigureFromConfigurationOptions.MakeGenericType(type); |
| | | |
| | | services.AddOptions(); |
| | | services.AddSingleton(iOptionsChangeTokenSource, |
| | | Activator.CreateInstance(configurationChangeTokenSource, Options.DefaultName, config) ?? throw new InvalidOperationException()); |
| | | return services.AddSingleton(iConfigureOptions, |
| | | Activator.CreateInstance(namedConfigureFromConfigurationOptions, Options.DefaultName, config) ?? throw new InvalidOperationException()); |
| | | } |
| | | |
| | | /// <summary>鑾峰彇閰嶇疆璺緞</summary> |
| | | /// <param name="optionsType">閫夐」绫诲瀷</param> |
| | | /// <returns></returns> |
| | | public static string GetConfigurationPath(Type optionsType) |
| | | { |
| | | var endPath = new[] { "Option", "Options" }; |
| | | var configurationPath = optionsType.Name; |
| | | foreach (var s in endPath) |
| | | { |
| | | if (configurationPath.EndsWith(s)) |
| | | { |
| | | return configurationPath[..^s.Length]; |
| | | } |
| | | } |
| | | |
| | | return configurationPath; |
| | | } |
| | | } |
| | | } |