console|

宣君

园龄:7年7个月粉丝:18关注:2

2023-09-01 17:44阅读: 1166评论: 0推荐: 0

.NET6读取appsettings.json配置

.NET6读取appsettings.json配置

基于.NET 6.0创建的WebAPI项目,自动生成的appsettings.json配置模板,在当前项目(dll)中可以通过构造函数注入Configuration来读取。

那么不在当前项目中怎么读取配置呢?例如下面这样的项目,appsesttings.jsonXuanjun.Blog.Server.API中,但是想在Xuanjun.Blog.Server.Core读取配置,怎么实现呢?

image

之所以非要在另一个项目中读取配置,是因为想将 Xuanjun.Blog.Server.API 只作为API库,业务都下沉到 Xuanjun.Blog.Server.Core 项目中,所以像数据库连接信息这样的配置都要在这个库中处理

实现代码如下:

/// <summary>
/// 全局配置
/// </summary>
public class GlobalConfigContext
{
static IConfiguration _configuration;
static GlobalConfigContext()
{
_configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", true, true).Build();
}
/// <summary>
/// 数据库连接信息
/// </summary>
public static XDbConfig DbConfig => _configuration.GetSection("DbConfig").Get<XDbConfig>();
}

这样就可以在任意地方读取配置了。

posted @   宣君  阅读(1166)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起