In a skeleton ASP.NET Core 7 project with top level statements, this is what you get:
var builder = WebApplication.Create(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
I want to add a DbContext
with:
builder.Services.AddDbContext<EntityDbContext>((provider, options) =>
{
var dbCfg = provider.GetRequiredService<IDatabaseConfig>();
options.UseSqlServer(dbCfg);
});
I have a library which registers appsettings.json
elements as DI services, which is where IDatabaseConfig
would come from. To wire that up in the past I've done:
var host = Host.CreateDefaultBuilder(args)
.ConfigureServices((hostBuilderContext, services) =>
{
// Provide environment override appsettings file
var env = hostBuilderContext.HostingEnvironment;
services.RegisterAppSettings<Config>($"appsettings.{env.EnvironmentName}.json");
.
.
.
})
With the top level statements and host builder approach in newer .NET where there is no ConfigureServices
method, how do I get access to the HostBuilderContext
in order to determine the HostingEnvironment
?