使用 WebApplicationFactory,在 Program.cs 执行之前添加配置源

With WebApplicationFactory, add configuration source before Program.cs executes

我正在使用新的最小 .NET 6 托管模型,并且我有一个集成测试。

显然 Program.cs 需要配置值,所以我想使用自定义 appsettings.Test.json 文件。文档说我可以使用 ConfigureAppConfiguration 但它的委托在 Program 之后运行,因此 Program 没有配置。这是添加到 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);
    }
}

如何向 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());

我可以将环境设置为 Test,然后在程序中执行:

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());

但这对吗?

不幸的是,根据 https://github.com/dotnet/aspnetcore/issues/37680

目前代码的编写方式是不可能的

我找到了一个解决方法,我在此处详述:https://github.com/dotnet/aspnetcore/issues/37680#issuecomment-1032922656

如果您覆盖 WebApplicationFactory<T>.CreateHost() 并在调用 base.CreateHost() 之前调用 IHostBuilder.ConfigureHostConfiguration(),您添加的配置将在 WebApplication.CreateBuilder()builder.Build() 之间可见。根据我的测试,它在您查看配置的所有不同位置(回调等)都是可见的。