You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单体项目如何从appSettings.json读取5个数据库连接字符串

单体项目读取多数据库连接字符串方案

1. 调整appSettings.json结构

把5个连接字符串统一放到ConnectionStrings根节点下,按照业务场景命名不同的键,示例配置如下:

{
  // 其他原有配置保留
  "ConnectionStrings": {
    "AtmWithdrawalDb": "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=atmwithdrawalstore;Integrated Security=True;",
    "OrderDb": "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=order_store;Integrated Security=True;",
    "UserDb": "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=user_store;Integrated Security=True;",
    "ProductDb": "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=product_store;Integrated Security=True;",
    "LogDb": "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=log_store;Integrated Security=True;"
  }
}

2. 代码读取逻辑

ASP.NET Core 场景

直接使用框架自带的IConfiguration接口的GetConnectionString方法读取,注册多DbContext示例:

var builder = WebApplication.CreateBuilder(args);

// 逐个注册对应业务的DbContext
builder.Services.AddDbContext<AtmWithdrawalDbContext>(opt => 
    opt.UseSqlServer(builder.Configuration.GetConnectionString("AtmWithdrawalDb")));
builder.Services.AddDbContext<OrderDbContext>(opt => 
    opt.UseSqlServer(builder.Configuration.GetConnectionString("OrderDb")));
builder.Services.AddDbContext<UserDbContext>(opt => 
    opt.UseSqlServer(builder.Configuration.GetConnectionString("UserDb")));
builder.Services.AddDbContext<ProductDbContext>(opt => 
    opt.UseSqlServer(builder.Configuration.GetConnectionString("ProductDb")));
builder.Services.AddDbContext<LogDbContext>(opt => 
    opt.UseSqlServer(builder.Configuration.GetConnectionString("LogDb")));

后续在业务类中直接注入对应DbContext即可使用,不需要手动管理连接字符串。

普通.NET 项目场景

先安装Microsoft.Extensions.Configuration.Json NuGet包,手动初始化配置后读取:

// 初始化配置实例
var config = new ConfigurationBuilder()
    .AddJsonFile("appSettings.json", optional: false, reloadOnChange: true)
    .Build();

// 按需读取对应连接字符串
string atmConn = config.GetConnectionString("AtmWithdrawalDb");
string orderConn = config.GetConnectionString("OrderDb");
string userConn = config.GetConnectionString("UserDb");
string productConn = config.GetConnectionString("ProductDb");
string logConn = config.GetConnectionString("LogDb");

注意:读取时的键名需要和appSettings.json中配置的键名完全一致,大小写敏感,避免读取为空。

内容的提问来源于stack exchange,提问作者John Inyang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 02:24:03