ASP.NET CORE配置信息

做个笔记,原文链接

除了应用 IOptions<T> .Value的方式对配置信息进行全局注册外可以应用的另一个微软给出的组件,需要依赖两个包

Microsoft.Extensions.Configuration.Binder

Microsoft.Extensions.Options.ConfigurationExtensions


然后一个扩展方法:

public static class ServiceCollectionExtensions
{
    public static TConfig ConfigurePOCO<TConfig>(this IServiceCollection services, IConfiguration configuration, Func<TConfig> pocoProvider) where TConfig : class
    {
        if (services == null) throw new ArgumentNullException(nameof(services));
        if (configuration == null) throw new ArgumentNullException(nameof(configuration));
        if (pocoProvider == null) throw new ArgumentNullException(nameof(pocoProvider));

        var config = pocoProvider();
        configuration.Bind(config);
        services.AddSingleton(config);
        return config;
    }

    public static TConfig ConfigurePOCO<TConfig>(this IServiceCollection services, IConfiguration configuration, TConfig config) where TConfig : class
    {
        if (services == null) throw new ArgumentNullException(nameof(services));
        if (configuration == null) throw new ArgumentNullException(nameof(configuration));
        if (config == null) throw new ArgumentNullException(nameof(config));

        configuration.Bind(config);
        services.AddSingleton(config);
        return config;
    }
}

注册的时候:

  var mySettings = new MySettings("foo"); 
  services.ConfigurePOCO(Configuration.GetSection("MySettings"), mySettings);
  //或者
  services.ConfigurePOCO(Configuration.GetSection("MySettings"), () => new MySettings("foo"));

就不需要像 IOptions<T>应用之前还得注册services.AddOptions()了。(多配置行代码在团队中对不熟悉又喜欢偷懒的人来说是很烦恼的。。)

而且程序在启动时将配置单例注入到内存要好过IOptions的“懒加载”模式,而且避免对象初始化错误造成的运行时错误。

 

原文地址:https://www.cnblogs.com/ylsforever/p/6184162.html