zoukankan      html  css  js  c++  java
  • .NET Core类库项目中如何读取appsettings.json中的配置

    这是一位朋友问我的问题,写篇随笔回答一下。有2种方法,一种叫丑陋的方法 —— IConfiguration ,一种叫优雅的方法 —— IOptions 。

    1)先看丑陋的方法

    比如在 RedisClient 中需要读取 appsettings.json 中的 redis 连接字符串:

    {
      "redis": {
        "ConnectionString": "xxx"
      }
    }

    需要在 RedisClient 的构造函数参数中添加 IConfiguration 接口,并通过它直接读取:

    public class RedisClient
    {
        private readonly string _connectionString;
    
        public RedisClient(IConfiguration configuration)
        {
            _connectionString = configuration.GetSection("redis")["ConnectionString"];
        }
    }

    然后在 Startup 的 ConfigureServices() 方法中进行注入:

    public IConfigurationRoot Configuration { get; }
    
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IConfiguration>(Configuration);     
    }

    2)接着看优雅的方法

    首先定义一个存放连接字符串的配置类 RedisOptions :

    public class RedisOptions
    {
        public string ConnectionString { get; set; }
    }

    然后给 RedisClient 的构造函数参数中添加 IOptions<RedisOptions> 接口,通过 IOptions<RedisOptions> 读取配置,RedisClient 无需关心 appsettings.json :

    public class RedisClient
    {
        private readonly RedisOptions _redisOptions;
    
        public RedisClient(IOptions<RedisOptions> redisOptions)
        {
            _redisOptions = redisOptions.Value;
        }
    }

    而 appsettings.json 中的配置可以在 Startup 的 ConfigureServices() 中注入进去:

    services.AddOptions();
    services.Configure<RedisOptions>(Configuration.GetSection("redis"));

    (注:使用上面的 Configure 方法需要安装 nuget 包 Microsoft.Extensions.Options.ConfigurationExtensions )

    作为类库的设计者,你可以更贴心些,写个扩展方法进行上面的注入操作。

  • 相关阅读:
    LeetCode Power of Three
    LeetCode Nim Game
    LeetCode,ugly number
    LeetCode Binary Tree Paths
    LeetCode Word Pattern
    LeetCode Bulls and Cows
    LeeCode Odd Even Linked List
    LeetCode twoSum
    549. Binary Tree Longest Consecutive Sequence II
    113. Path Sum II
  • 原文地址:https://www.cnblogs.com/dudu/p/6828045.html
Copyright © 2011-2022 走看看