.net core 使用 IOption 依赖注入获取配置值

1 appsettins 配置

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Theme": {
    "Name": "Blue",
    "Color": "#0921DC"
  }
}

2 配置节Themes对应的选项类

namespace WebApi_Test.Options
{
    public class ThemeOptions
    {
        public string Name { get; set; }

        public string Color { get; set; }
    }
}

3 ServiceCollection 扩展类

using WebApi_Test.Options;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class ConfigurableOptionsServiceCollectionExtensions
    {
        /// <summary>
        /// 添加选项配置
        /// </summary>
        /// <typeparam name="TOptions"></typeparam>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <param name="configKey">选项类绑定的对应configuration的配置节key</param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static IServiceCollection AddConfigurableOptions<TOptions>(this IServiceCollection services, IConfiguration configuration, string configKey, Action<TOptions> action) where TOptions : class
        {
            var optionsConfigure = services.AddOptions<TOptions>()
                .Bind(configuration.GetSection(configKey), options =>
                {
                    options.BindNonPublicProperties = true;
                })
                .ValidateDataAnnotations();

            if (action != null)
                optionsConfigure.PostConfigure(action);

            return services;
        }
    }
}

4 添加注册测试选项类

            builder.Services.AddConfigurableOptions<ThemeOptions>(builder.Configuration, "Theme", options => {
                options.Color = "new Color";
            });

5 通过依赖注入测试获取配置

        private ThemeOptions _themeOptions;

        public WeatherForecastController(IOptions<ThemeOptions> themeOptions)
        {
            _themeOptions = themeOptions.Value;
        }

 

posted @ 2023-02-14 17:12  温故纳新  阅读(195)  评论(1编辑  收藏  举报