我在控制台工作人员服务应用程序中有此配置:
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath("/home/pi/config/")
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", true, true)
.AddEnvironmentVariables()
.Build();
然后我与主机一起使用:
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices((cotext, services) =>
{
services.Configure<Settings>(configuration.GetSection(nameof(Settings)));
services.AddSingleton<IMyService, MyService>();
services.AddHostedService<Worker>();
})
.Build();
那么在MyService类实例中,如何获取有关使用了哪个配置文件及其路径的信息?将 IConfiguration 注入 MyService 后,似乎没有任何配置文件的信息。
AppSettings
不要根据环境选择性加载。但发生的情况是,默认文件首先加载,然后任何其他文件将覆盖任何现有的默认设置。
根据您的代码:
appsettings.json
将作为非可选添加为默认文件。这意味着如果文件不存在,应用程序将失败。
然后特定于环境的
appsettings.{env}.json
将作为可选加载。如果它不存在,则什么也不会发生。如果存在,它可能包含的任何设置都将覆盖默认设置。
这基本上意味着不存在“已使用哪个配置文件”,因为如果满足条件,则可以加载多个文件。但是要检查您的应用程序运行在哪个环境中,您可以使用 IHostEnvironment,例如调用 IHostEnvironment.EnvironmentName
您可以从文档中阅读有关 .NET 中的配置的更多信息,该文档还包含有关 配置提供程序 和 实现自定义配置提供程序的信息。
您还可以阅读这篇关于 .NET Core 依赖注入与配置的文章。
我刚刚做了这个
var environmentName = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
IServiceCollection services = new ServiceCollection();
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.json", true, true)
.AddJsonFile($"appsettings.{environmentName}.json", true, true)
.AddEnvironmentVariables()
.Build();
在我的 appsettings.json 和 appsettings 中。
"AppSettingsFileName": "appsettings.Test.json"
然后就可以这样做(或console.writeline或其他)
logger.LogInformation("Environment:{environmentName}",environmentName);
logger.LogInformation("SettingFile:{settingsFile}",config["AppSettingsFileName"]);