是否可以在 WebHost 启动后添加到 IConfiguration?

Is it possible to add to IConfiguration after the WebHost has started?

我正在使用 AWS Systems Manager Parameter Store 保存用于在我的 .NET Core 应用程序中动态构建 DbContext 的数据库连接字符串

我正在使用 .NET Core AWS 配置提供程序(来自 https://aws.amazon.com/blogs/developer/net-core-configuration-provider-for-aws-systems-manager/),它在运行时将我的参数注入 IConfiguration。

目前我必须在代码中保留我的 AWS 访问权限 key/secret,以便 ConfigurationBuilder 可以访问它,但我想将其移出代码库并将其存储在 appsettings 或类似的地方。

这是我创建启动时调用的虚拟主机构建器的方法

public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
    var webHost = WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>();

    AWSCredentials credentials = new BasicAWSCredentials("xxxx", "xxxx");

    AWSOptions options = new AWSOptions()
    {
        Credentials = credentials,
        Region = Amazon.RegionEndpoint.USEast2
    };

    webHost.ConfigureAppConfiguration(config =>
    {
        config.AddJsonFile("appsettings.json");
        config.AddSystemsManager("/ParameterPath", options, reloadAfter: new System.TimeSpan(0, 1, 0)); // Reload every minute
    });

 return webHost;
}

我需要能够从某处注入 BasicAWSCredentials 参数。

您需要访问已构建的配置才能检索您要查找的信息。

考虑构建一个来检索所需的凭据

public static IWebHostBuilder CreateWebHostBuilder(string[] args) {
    var webHost = WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>();

    var configuration = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .Build();

    var access_key = configuration.GetValue<string>("access_key:path_here");
    var secret_key = configuration.GetValue<string>("secret_key:path_here");

    AWSCredentials credentials = new BasicAWSCredentials(access_key, secret_key);

    AWSOptions options = new AWSOptions() {
        Credentials = credentials,
        Region = Amazon.RegionEndpoint.USEast2
    };

    webHost.ConfigureAppConfiguration(config => {
        config.AddJsonFile("appsettings.json");
        config.AddSystemsManager("/ParameterPath", options, reloadAfter: new System.TimeSpan(0, 1, 0)); // Reload every minute
    });

    return webHost;
}

我还建议查看文档中的 Configuring AWS Credentials 以使用 SDK 找到存储和检索凭据的可能替代方法。