.net 5 使用 Option注入 获取配置值

1 编写 ConsulServerOptions 类

    public class ConsulServerOptions
    {
        public string? IP { get; set; }
        public int Port { get; set; }
        public string? Datacenter { get; set; }
    }

2 appsettings.json 文件里配置consul

 

 

3 在 Startu 中的 ConfigureServices,注册  ConsulServerOptions

services.Configure<ConsulServerOptions>(Configuration.GetSection(nameof(ConsulServerOptions)));

4 通过构造函数获取选项实例

        private readonly ILogger<WeatherForecastController> _logger;
        private ConsulServerOptions _consulClientOptions = null;

        public WeatherForecastController(IOptionsMonitor<ConsulServerOptions> consulClientOptions,ILogger<WeatherForecastController> logger)
        {
            _consulClientOptions = consulClientOptions.CurrentValue;
            _logger = logger;
        }

5 测试

 

posted @ 2022-06-03 10:13  温故纳新  阅读(97)  评论(0编辑  收藏  举报