Reputation: 4594
I have a layered architecture for a project as follows.
MyProject.Web <-- ASP.NET Core app
MyProject.BusinessLogic <-- Class Library
MyProject.DataAccess <-- Class Library
Web
project references BusinessLogic
, which in turn references DataAccess
.
The connection string is stored in appsettings.json
in Web
project as follows.
{
"ConnectionStrings": {
"LocalDatabase": "Server=..."
},
// ...
}
}
How do I get a connection string in the DataAccess
project?
Upvotes: 1
Views: 2674
Reputation: 21
Try this:
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");
}
Remember 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;"
}
}
Upvotes: 2