You can use builder.Configuration
. In this example, the connection string is retrieved in the second line of actual code:
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("TodoDb")
?? "Data Source=todos.db";
builder.Services.AddSqlite<TodoDb>(connectionString)
.AddDatabaseDeveloperPageExceptionFilter();
The WebApplicationBuilder.Configuration property is a Microsoft.Extensions.ConfigurationManager instance that implements IConfigurationRoot
and IConfiguration
, so it can be used to load config settings or use extension methods like GetConnectionString
Once the application is built, configuration is accessible through the WebApplication.Configuration property. This is just a call to Services.GetRequiredService<IConfiguration>()
:
public IConfiguration Configuration =>
_host.Services.GetRequiredService<IConfiguration>();