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

     

  • 相关阅读:
    [转载]Matlab实用小技巧
    Matlab rand randn randint
    Matlab取整
    Mathtype报错:MathType has detected an error in....
    [转载]十大编程算法助程序员走上高手之路
    (转)Free函数的参数一定要是malloc返回的那个指针
    sizeof,一个其貌不扬的家伙(转)
    ISO C Random Number Functions
    srand() rand() time(0)
    IOS之文件夹创建、删除,图片在本地的保存和加载
  • 原文地址:https://www.cnblogs.com/ylsforever/p/6184162.html
Copyright © 2011-2022 走看看