zhaolei
8 days ago 921de2254ff5712a44ed8575ee8efe34252f6603
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using Microsoft.AspNetCore;
using System;
 
namespace Microsoft.Extensions.Configuration
{
    /// <summary>
    /// 配置文件配置小节映射操作类
    /// </summary>
    public static class ConfigurationExtensions
    {
        /// <summary>
        /// 通过类型获得配置小节 读取顺序 Key > Name > FullName > ProviderAlias
        /// </summary>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IConfigurationSection GetSection<T>(this IConfiguration configuration)
        {
            var providerType = typeof(T);
            var section = configuration.GetSection(providerType.Name);
            if (!section.Exists()) section = configuration.GetSection(providerType.FullName);
            return section;
        }
 
        /// <summary>
        /// 通过指定 Section 名称 获得配置项类实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="configuration"></param>
        /// <param name="valueFactory">默认值</param>
        /// <returns></returns>
        public static T GetOption<T>(this IConfiguration configuration, Func<T> valueFactory) where T : class
        {
            var ret = default(T);
            var providerType = typeof(T);
            var section = configuration.GetSection(providerType.Name);
            if (!section.Exists()) section = configuration.GetSection(providerType.FullName);
            if (section.Exists()) ret = section.Get<T>();
            if (ret == default) ret = valueFactory.Invoke();
            return ret;
        }
 
        /// <summary>
        /// 获得 配置文件中 BootstrapAdminAuthenticationOptions 实例
        /// </summary>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static BootstrapAdminAuthenticationOptions GetBootstrapAdminAuthenticationOptions(this IConfiguration configuration) => configuration.GetSection<BootstrapAdminAuthenticationOptions>().Get<BootstrapAdminAuthenticationOptions>();
    }
}