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

     

  • 相关阅读:
    David Cutler NT之父
    VS2012 RC 编译Qt 4.8.2完整过程
    vm demo加固分析
    IDA dump so
    博客园首次发帖
    WebRTC本地选择codec(web本地模拟)
    Android 摄像头预览悬浮窗,可拖动,可显示在其他app上方
    [译] 清除浮动的新方法
    《学习HTML5游戏编程》译记
    Web中的Tip组件实现
  • 原文地址:https://www.cnblogs.com/ylsforever/p/6184162.html
Copyright © 2011-2022 走看看