1

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Stephen York
  • 1,247
  • 1
  • 13
  • 42

1 Answers1

2

You need to use your library in Host like this:


var builder = WebApplication.CreateBuilder(args);

builder.Host.ConfigureServices((hostBuilderContext, services) =>
{
    var env = hostBuilderContext.HostingEnvironment;
    services.RegisterAppSettings<Config>($"appsettings.{env.EnvironmentName}.json");
});

Or if you only need the environment name, so this is the way:

var builder = WebApplication.CreateBuilder(args);

builder.Services.RegisterAppSettings<Config>($"appsettings.{builder.Environment.EnvironmentName}.json");
sa-es-ir
  • 3,722
  • 2
  • 13
  • 31
  • Just curious, if I needed to go with `builder.Host` then which nuget package to I need to install. I'm not getting "find package" with intellisense and can't find the documentation page about it. – Stephen York Apr 02 '23 at 23:35
  • @StephenYork what is your .net version? Mine is .net6 and I can see it in the program.cs – sa-es-ir Apr 03 '23 at 04:23