I am using the code below to retrieve the connection string and it works fine. However, the configuration object has to be passed through the layers. Previous versions of .Net would allow me to get the connection string directly in the data layer. So can I still do that (and how do I do that) or do I need to pass the configuration object through the application as I do now?
In startup.cs
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton(_ => Configuration);
...
}
MyController.cs
public class MyController : Controller
{
protected readonly IConfiguration Configuration;
public MyController(IConfiguration configuration)
{
Configuration = configuration;
}
public IActionResult ListRecords()
{
DatabaseContext ctx = new DatabaseContext(Configuration);
return View();
}
}
DatabaseContext.cs
public class DatabaseContext : DbContext
{
private readonly IConfiguration config;
public DatabaseContext(IConfiguration config)
{
this.config = config;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(config["ConnectionStrings:Dev"]);
}
}