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

     

  • 相关阅读:
    thinkphp header模块中的CSS格式也要写在home页中,不然无效
    thinkphp header模块中设为首页的JS代码需要写在HOME页中
    dubbo框架-学习-dubbo原理
    java-面试题为什么redis这么快
    jsp学习——九大内置对象
    日志平台使用记录
    java-消息队列相关-activeMQ
    java——比较难和底层的面试题
    学习之道——感觉东西多不知道如何下手怎么办
    java-Freemarker-模板引擎学习
  • 原文地址:https://www.cnblogs.com/ylsforever/p/6184162.html
Copyright © 2011-2022 走看看