using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
namespace EntrustSettle.Common.Option.Core;
public static class ConfigurableOptions
{
/// 添加选项配置
/// 选项类型
/// 服务集合
/// 服务集合
public static IServiceCollection AddConfigurableOptions(this IServiceCollection services)
where TOptions : class, IConfigurableOptions
{
Type optionsType = typeof(TOptions);
string path = GetConfigurationPath(optionsType);
services.Configure(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());
}
/// 获取配置路径
/// 选项类型
///
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;
}
}