我有一个项目的分层架构如下。
MyProject.Web <-- ASP.NET Core app
MyProject.BusinessLogic <-- Class Library
MyProject.DataAccess <-- Class Library
Web
项目引用BusinessLogic
,后者又引用DataAccess
。
连接字符串存储在appsettings.json
项目的Web
中,如下所示。
{
"ConnectionStrings": {
"LocalDatabase": "Server=..."
},
// ...
}
}
如何在DataAccess
项目中获取连接字符串?
答案 0 :(得分:1)
试试这个:
public static IConfiguration Configuration { get; set; }
private string GetConnectionString()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
return Configuration.GetConnectionString("DefaultConnection");
}
记住appsetting.json
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
},
"ConnectionStrings": {
"DefaultConnection": "Server=((local));Database=database;Trusted_Connection=True;user id=xx;password=xxxx;"
}
}