新建控制台
static void Main(string[] args)
{
Console.WriteLine("Hello World!"); //获取应用程序的当前工作目录 包含当前工作目录路径的字符串,但不包含//以反斜杠(\)结束。
var pathToContentRoot = Directory.GetCurrentDirectory();
//用于构建基于键/值的配置设置,以便在应用程序中使用
var builder = new ConfigurationBuilder()
.SetBasePath(pathToContentRoot)//将基于文件的提供程序的FileProvider设置为PhysicalFileProvider基本路径
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)//在构建器的路径中添加JSON配置提供程序
.AddEnvironmentVariables();//添加读取的Microsoft.Extensions.Configuration.IConfigurationProvider来自环境变量的配置值
Coin.Service.Models.CoinAppSettings.CreateInstence(builder.Build());// 获取具有指定键的配置子节 这边开始读取配置文件了!!! Console.WriteLine("Hello World!");
Console.ReadKey();
}
CreateInstence 这个方法的实现 及 CoinAppSettings这个类库的代码如下
public class CoinAppSettings
{
public DbConnection ConnectionStrings { get; }
public AppSettings AppSettings { get; }
public static CoinAppSettings Instance { get; private set; }
public static void CreateInstence(IConfigurationRoot builder)
{
Instance = new CoinAppSettings(builder);
}
public CoinAppSettings(IConfigurationRoot builder)
{
this.ConnectionStrings = new DbConnection(builder.GetSection("ConnectionStrings"));
this.AppSettings = new AppSettings(builder.GetSection("AppSettings"));
}
}
public class AppSettings
{
public string ApiHost { get; }
public AppSettings(IConfigurationSection section)
{
this.ApiHost = section.GetSection("ApiHost").Value;
}
}