I am using the new minimal .NET 6 hosting model, and I have an integration test.
Obviously Program.cs needs configuration values, so I want to use a custom appsettings.Test.json file. Docs say I can use ConfigureAppConfiguration but its delegate runs after Program, hence Program has no configuration. Here's the code added to the Minimal API Playground sample code:
internal class PlaygroundApplication : WebApplicationFactory<Program>
{
private readonly string _environment;
public PlaygroundApplication(string environment = "Development")
{
_environment = environment;
}
protected override IHost CreateHost(IHostBuilder builder)
{
builder.UseEnvironment(_environment);
builder.ConfigureAppConfiguration(config =>
{
config.AddJsonFile(appSettings); // runs AFTER Program.cs
});
// Add mock/test services to the builder here
builder.ConfigureServices(services =>
{
});
return base.CreateHost(builder);
}
}
How can I provide configuration to Program.cs?
var builder = WebApplication.CreateBuilder(args);
var keyVaultName = builder.Configuration["KeyVaultName"]; // null
builder.Configuration.AddAzureKeyVault(new SecretClient(
new Uri($"https://{keyVaultName}.vault.azure.net/"),
new DefaultAzureCredential()), new KeyVaultSecretManager());
I can set environment to Testand then in Program do:
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json");
var keyVaultName = builder.Configuration["KeyVaultName"]; // has value from json
builder.Configuration.AddAzureKeyVault(new SecretClient(
new Uri($"https://{keyVaultName}.vault.azure.net/"),
new DefaultAzureCredential()), new KeyVaultSecretManager());
But is that correct?