In older versions of ASP.Net core you had the startup.cs file where you would do a lot of the work including reading and setting the application environment then based on that you could read different version of the appsettings.json file. In the new ASP.Net Core 7 they got rid of Startup.cs and greatly streamlined the program.cs files. Now I can't figure out how to read the environment and then pass Entity Framework 7 my connection string. Looking around all the answers I find don't apply to version 7 or tell you to undo all the work in 7 by remaking the entire Startup.cs file. How are we supposed to inject the connection string based off the environment in .Net 7?
I do have the code to read from the base appsettings.json file and that works, there is also a section to read the environment but it get setup AFTER the DbContext injection. Here is my program.cs file and I am just lost on what needs to be updated. I looked at the microsoft docs but did not see anything applying to environements and injection of the string.
var builder = WebApplication.CreateBuilder(args);
//Add Services (builder.Services.AddScoped<IService, Service>();
builder.Services.AddScoped<INavigationHelper, NavigationHelper>();
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
builder.Services.AddRazorPages().AddMicrosoftIdentityUI();
builder.Services.AddDbContext<SiteDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("Database")));
var app = builder.Build();
if (!app.Environment.IsDevelopment()) { app.UseHsts(); }
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.MapControllers();
app.Run();
appsettings.json:
{
"AzureAd":
{
"Instance": "https://login.microsoftonline.com/",
"Domain": "",
"TenantId": "",
"ClientId": "",
"CallbackPath": "",
"ClientSecret": "Client secret from app-registration. Check user secrets/azure portal.",
"ClientCertificates":
[
]
},
"Logging":
{
"LogLevel":
{
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings":
{
"Database": ""
}
}
appsettings.development.json
{
"Logging":
{
"LogLevel":
{
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
},
"ConnectionStrings":
{
"Database": ""
}
}
}