添加一个Json配置文件,名称随意,这里暂定名称为xxx.json,配置文件里面添加一个Json对象,例如
{
"AwardSetting": {
"ServiceFeeProportion": 0.01,
"ExtractProportion": 0.09,
"ExtractReceiveAddress": ""
}
}
添加一个类,名称要和定义的Json对象定义的一致,例如
namespace Example.Award
{
public class AwardSetting
{
public double ServiceFeeProportion { get; set; }
public double ExtractProportion { get; set; }
public string ExtractReceiveAddress { get; set; }
}
}
配置解析类,注意引入Microsoft.Extensions.Options.ConfigurationExtensions包, 注意using的包
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace FiiiChain.MiningPool.Award.Tools
{
public class ConfigurationTool
{
public T GetAppSettings<T>(string key) where T : class, new()
{
IConfiguration config = new ConfigurationBuilder()
.Add(new JsonConfigurationSource { Path = "xxx.json", ReloadOnChange = true })
.Build();
T appconfig = new ServiceCollection()
.AddOptions()
.Configure<T>(config.GetSection(key))
.BuildServiceProvider()
.GetService<IOptions<T>>()
.Value;
return appconfig;
}
}
}
在调用的地方
ConfigurationTool tool = new ConfigurationTool();
AwardSetting setting = tool.GetAppSettings<AwardSetting>("AwardSetting");