DotNetCore跨平臺~關於appsettings.json裡各種配置項的讀取
阿新 • • 發佈:2018-12-30
對於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;
感謝各位的閱讀!