zoukankan      html  css  js  c++  java
  • 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的“懒加载”模式,而且避免对象初始化错误造成的运行时错误。

     

  • 相关阅读:
    windows下nginx的安装及使用
    JAVA面试经历
    项目框架搭建
    383. Ransom Note
    Add to List 349. Intersection of Two Arrays
    171. Excel Sheet Column Number
    463. Island Perimeter
    669. Trim a Binary Search Tree
    496. Next Greater Element I
    637. Average of Levels in Binary Tree
  • 原文地址:https://www.cnblogs.com/ylsforever/p/6184162.html
Copyright © 2011-2022 走看看