方法一直接读取JSON节点值:
"AppSettings": { "CacheDays": 30, }
public string GetIntelligenceApiUrl { get { var cacheDays = new ConfigurationHelper().Get<string>("AppSettings:CacheDays"); return cacheDays; } }
方法一的操作类:
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Json; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using System.IO; /// <summary> /// 读取配置文件 /// </summary> public class ConfigurationHelper { public IConfiguration _config { get; set; } public ConfigurationHelper() { _config = new ConfigurationBuilder() .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })//ReloadOnChange = true 当appsettings.json被修改时重新加载 .Build(); } public T GetAppSettings<T>(string key) where T : class, new() { var appconfig = new ServiceCollection() .AddOptions() .Configure<T>(_config.GetSection(key)) .BuildServiceProvider() .GetService<IOptions<T>>() .Value; return appconfig; } public T Get<T>(string key) { IConfiguration config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", true, true).Build(); return config.GetSection(key).Get<T>(); } //public T GetAppsettings<T>(string key) where T : class, new() //{ // string keyDir = System.IO.Directory.GetCurrentDirectory(); // IConfiguration config = new ConfigurationBuilder() // .SetBasePath(keyDir) // .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })//ReloadOnChange = true 当appsettings.json被修改时重新加载 // .Build(); // var appconfig = new ServiceCollection() // .AddOptions() // .Configure<T>(config.GetSection(key)) // .BuildServiceProvider() // .GetService<IOptions<T>>() // .Value; // return appconfig; //} /// <summary> /// 通过强类型绑定读取配置 /// </summary> /// <typeparam name="Entity">要绑定的类型</typeparam> /// <param name="keyPath">配置文件路径</param> /// <returns>绑定的类</returns> public Entity GetSectionObject<Entity>(string keyPath = null) where Entity : new() { var entity = new Entity(); if (string.IsNullOrEmpty(keyPath)) { //将appsettings.json全部配置绑定到模型 _config.Bind(entity); } else { //将指定路径下的配置项绑定到模型 var section = _config.GetSection(keyPath); section.Bind(entity); } return entity; } }
方法二通过注入方式:
using Microsoft.Extensions.Configuration; public class AppSettingOptions : IAppSetting { public AppSettingOptions() { var configBuilder = new ConfigurationBuilder(); configBuilder.AddJsonFile("appsettings.json"); var config = configBuilder.Build(); var section = config.GetSection("AppSettings"); section.Bind(this); } public int CacheDays { get; set; } } public interface ISingle { } public interface IScope { } public interface ITrans { } public interface IAppSetting : IScope { }
方法二注入:
readonly AppSettingOptions _config; public BoProcessIntelligenceShareHolder(IAppSetting config) { _config = (AppSettingOptions)config; }