一、创建AppSetting帮助类
public class AppSetting
{
private static readonly object objLock = new object(); //锁
private static AppSetting instance = null;
private IConfigurationRoot Config { get; }
private AppSetting(string environmentName)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)//增加环境配置文件,新建项目默认有
.AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: true);
Config = builder.Build();
}
//加锁
public static AppSetting GetInstance(string environmentName)
{
if (instance == null)
{
lock (objLock)
{
if (instance == null)
{
instance = new AppSetting(environmentName);
}
}
}
return instance;
}
//读取方法
public string GetConfig(string name)
{
var val = this.Config.GetSection(name).Value;
return val;
}
public string[] GetArray(string name)
{
var val = this.Config.GetSection(name).Get<string[]>();
return val;
}
}
注:使用.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
这种方法可以保证可以修改正在运行的dotnet core 程序,不需要重启程序
未完待续。。。