zhaolei
2020-11-20 4a2e5b9a21940f11757be37d99f0944e240e908b
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#if !NET45
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
 
namespace Prow.Configuration
{
    /// <summary>
    /// 配置项操作扩展类
    /// </summary>
    [Obsolete("下个版本移除此类")]
    public static class ConfigurationManager
    {
        /// <summary>
        /// 获得 当前应用 IConfiguration 实例
        /// </summary>
        public static IConfiguration AppSettings { get { return _lazy.Value; } }
 
        /// <summary>
        /// 通过指定 Section 名称 获得强类型值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">配置项键值</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static T GetValue<T>(string key, T defaultValue) => AppSettings.GetValue(key, defaultValue);
 
#nullable disable
        private static Lazy<IConfiguration> _lazy;
        /// <summary>
        /// 通过指定 Section 名称 获得配置项类实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="valueFactory">默认值</param>
        /// <returns></returns>
        public static T Get<T>(Func<T> valueFactory = null)
        {
            var section = AppSettings.GetSection<T>();
            T ret = default;
            if (section.Exists()) ret = section.Get<T>();
            if (ret == null && valueFactory != null) ret = valueFactory.Invoke();
            return ret;
        }
#nullable restore
 
        /// <summary>
        /// 通过指定 Section 名称 获取子节点配置项 IConfigurationSection 实例
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static IConfiguration GetSection(string key) => AppSettings.GetSection(key);
 
        /// <summary>
        /// 通过指定 Section 名称 获取子节点配置项 IConfigurationSection 实例
        /// </summary>
        /// <returns></returns>
        public static IConfiguration GetSection<T>() => AppSettings.GetSection<T>();
 
        /// <summary>
        /// Services 注入时调用
        /// </summary>
        /// <param name="services"></param>
        internal static void RegisterConfigurationManager(this IServiceCollection services)
        {
            _lazy = new Lazy<IConfiguration>(() =>
            {
                return services.BuildServiceProvider().GetRequiredService<IConfiguration>();
            });
        }
    }
}
#endif