DotNetCore跨平台~关于appsettings.json里各种配置项的读取

回到目录

对于dotnet Core来说,依赖注入的集成无疑是最大的亮点,它主要用在服务注册与注入和配置文件注册与注入上面,我们一般会在程序入口先注册服务或者文件,然后在需要的地方使用注入即可,下面主要介绍一下实体配置和集合配置的方式.

看一下配置文件代码段

 "JobConfig": [
    {
      "JobTypeDll": "TaskServicePool",
      "JobTypeFullName": "TaskServicePool.Jobs.SendMessageJob",
      "Cron": "0/5 * * * * ?"
    },
    {
      "JobTypeDll": "TaskServicePool",
      "JobTypeFullName": "TaskServicePool.Jobs.AsyncCustomerJob",
      "Cron": "0/10 * * * * ?"
    },
    {
      "JobTypeDll": "TaskServicePool",
      "JobTypeFullName": "Pilipa.TaskServicePool.Jobs.SendEmailJob",
      "Cron": "0/1 * * * * ?"
    }
  ],

无论是实体还是集合,都应该先把配置文件注册一下

 var config = new ConfigurationBuilder()
                  .SetBasePath(Directory.GetCurrentDirectory())
                  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                  .Build();

实体配置的注入如下

           //实体配置
            var spOne = new ServiceCollection().AddOptions()
                        .Configure<RedisConfiguration>(config.GetSection("RedisConfiguration"))
                        .BuildServiceProvider();
            var jobConfigList2 = spOne.GetService<IOptions<RedisConfiguration>>().Value;

集合的注入如下

           //集合配置
            var spList = new ServiceCollection().AddOptions()
                         .Configure<List<JobConfig>>(config.GetSection("JobConfig"))
                         .BuildServiceProvider();
            var jobConfigList1 = spList.GetService<IOptions<List<JobConfig>>>().Value;

回到目录

感谢各位的阅读!

posted @ 2017-08-28 10:54  张占岭  阅读(1030)  评论(2编辑  收藏  举报