Reputation: 133
I have an ASP .NET MVC 6 and Entity Framework 6, divided into layers , how do I get the connection string in the DAL layer in my DbContext ? The connection string is in appsettings.json file like this:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Verbose",
"System": "Information",
"Microsoft": "Information"
}
},
"Data": {
"DefaultConnection": {
"ConnectionString": "",
}
}
}
Upvotes: 0
Views: 156
Reputation: 3497
If you have the connection string in appsettings.json
you want to build a configuration object first:
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
var configuration = builder.Build();
This should probably be in Startup
's ctor. You can then store the configuration
object in a field. Let's say a _configuration
field.
Then you can do
// _connectionString is also a field.
_connectionString = _configuration["Data:DefaultConnection"];
Your DbContext
:
public class AppDbContext : DbContext
{
public AppDbContext(string connectionString) : base(connectionString)
{
}
}
The you can register your AppDbContext
in ConfigureServices
as:
services.AddScoped(_ => new AppDbContext(_connectionString));
Upvotes: 3