Skip to content

Add support for application-specific settings files in Host defaults #116987

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Jun 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public sealed class HostApplicationBuilder : IHostApplicationBuilder
/// <item><description>load host <see cref="IConfiguration"/> from "DOTNET_" prefixed environment variables</description></item>
/// <item><description>load host <see cref="IConfiguration"/> from supplied command line args</description></item>
/// <item><description>load app <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostEnvironment.EnvironmentName"/>].json'</description></item>
/// <item><description>load app <see cref="IConfiguration"/> from '[<see cref="IHostEnvironment.ApplicationName"/>].settings.json' and '[<see cref="IHostEnvironment.ApplicationName"/>].settings.[<see cref="IHostEnvironment.EnvironmentName"/>].json' when <see cref="IHostEnvironment.ApplicationName"/> is not empty</description></item>
/// <item><description>load app <see cref="IConfiguration"/> from User Secrets when <see cref="IHostEnvironment.EnvironmentName"/> is 'Development' using the entry assembly</description></item>
/// <item><description>load app <see cref="IConfiguration"/> from environment variables</description></item>
/// <item><description>load app <see cref="IConfiguration"/> from supplied command line args</description></item>
Expand All @@ -64,6 +65,7 @@ public HostApplicationBuilder()
/// <item><description>load host <see cref="IConfiguration"/> from "DOTNET_" prefixed environment variables</description></item>
/// <item><description>load host <see cref="IConfiguration"/> from supplied command line args</description></item>
/// <item><description>load app <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostEnvironment.EnvironmentName"/>].json'</description></item>
/// <item><description>load app <see cref="IConfiguration"/> from '[<see cref="IHostEnvironment.ApplicationName"/>].settings.json' and '[<see cref="IHostEnvironment.ApplicationName"/>].settings.[<see cref="IHostEnvironment.EnvironmentName"/>].json' when <see cref="IHostEnvironment.ApplicationName"/> is not empty</description></item>
/// <item><description>load app <see cref="IConfiguration"/> from User Secrets when <see cref="IHostEnvironment.EnvironmentName"/> is 'Development' using the entry assembly</description></item>
/// <item><description>load app <see cref="IConfiguration"/> from environment variables</description></item>
/// <item><description>load app <see cref="IConfiguration"/> from supplied command line args</description></item>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ public static IHostBuilder ConfigureContainer<TContainerBuilder>(this IHostBuild
/// * load host <see cref="IConfiguration"/> from "DOTNET_" prefixed environment variables
/// * load host <see cref="IConfiguration"/> from supplied command line args
/// * load app <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostEnvironment.EnvironmentName"/>].json'
/// * load app <see cref="IConfiguration"/> from '[<see cref="IHostEnvironment.ApplicationName"/>].settings.json' and '[<see cref="IHostEnvironment.ApplicationName"/>].settings.[<see cref="IHostEnvironment.EnvironmentName"/>].json' when <see cref="IHostEnvironment.ApplicationName"/> is not empty
/// * load app <see cref="IConfiguration"/> from User Secrets when <see cref="IHostEnvironment.EnvironmentName"/> is 'Development' using the entry assembly
/// * load app <see cref="IConfiguration"/> from environment variables
/// * load app <see cref="IConfiguration"/> from supplied command line args
Expand Down Expand Up @@ -241,6 +242,14 @@ internal static void ApplyDefaultAppConfiguration(HostBuilderContext hostingCont
appConfigBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: reloadOnChange)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: reloadOnChange);

if (env.ApplicationName is { Length: > 0 })
{
string sanitizedApplicationName = env.ApplicationName.Replace(Path.DirectorySeparatorChar, '_')
.Replace(Path.AltDirectorySeparatorChar, '_');
appConfigBuilder.AddJsonFile($"{sanitizedApplicationName}.settings.json", optional: true, reloadOnChange: reloadOnChange)
.AddJsonFile($"{sanitizedApplicationName}.settings.{env.EnvironmentName}.json", optional: true, reloadOnChange: reloadOnChange);
}

if (env.IsDevelopment() && env.ApplicationName is { Length: > 0 })
{
try
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -826,6 +826,160 @@ private class ServiceC
public ServiceC(ServiceD serviceD) { }
}

[Fact]
public void ConfigureDefaults_LoadsApplicationSpecificSettings()
{
using TempDirectory tempDir = new();
string appSettingsPath = Path.Combine(tempDir.Path, "testapp.settings.json");
string appSettingsEnvPath = Path.Combine(tempDir.Path, "testapp.settings.Production.json");

// Create test configuration files
File.WriteAllText(appSettingsPath, """{"TestKey": "AppValue"}""");
File.WriteAllText(appSettingsEnvPath, """{"TestKey": "AppEnvValue", "EnvKey": "EnvValue"}""");

using var host = new HostBuilder()
.ConfigureDefaults(args: null)
.UseContentRoot(tempDir.Path)
.ConfigureHostConfiguration(config =>
{
config.AddInMemoryCollection(new[]
{
new KeyValuePair<string, string>(HostDefaults.ApplicationKey, "testapp"),
new KeyValuePair<string, string>(HostDefaults.EnvironmentKey, "Production")
});
})
.Build();

var configuration = host.Services.GetRequiredService<IConfiguration>();

// Verify that app-specific environment settings override app-specific settings
Assert.Equal("AppEnvValue", configuration["TestKey"]);
Assert.Equal("EnvValue", configuration["EnvKey"]);
}

[Fact]
public void ConfigureDefaults_LoadsApplicationSpecificSettings_WithDevelopmentEnvironment()
{
using TempDirectory tempDir = new();
string appSettingsPath = Path.Combine(tempDir.Path, "testapp.settings.json");
string appSettingsEnvPath = Path.Combine(tempDir.Path, "testapp.settings.Production.json");

// Create test configuration files
File.WriteAllText(appSettingsPath, """{"TestKey": "AppValue"}""");
File.WriteAllText(appSettingsEnvPath, """{"TestKey": "ProductionValue", "ProductionKey": "ProductionValue"}""");

using var host = new HostBuilder()
.ConfigureDefaults(args: null)
.UseContentRoot(tempDir.Path)
.ConfigureHostConfiguration(config =>
{
config.AddInMemoryCollection(new[]
{
new KeyValuePair<string, string>(HostDefaults.ApplicationKey, "testapp"),
new KeyValuePair<string, string>(HostDefaults.EnvironmentKey, "Development")
});
})
.Build();

var configuration = host.Services.GetRequiredService<IConfiguration>();

// Verify that Production-specific file is not loaded when running in Development environment
Assert.Equal("AppValue", configuration["TestKey"]); // Should come from base settings, not Production
Assert.Null(configuration["ProductionKey"]); // Should not be loaded from Production file
}

[Fact]
public void ConfigureDefaults_DoesNotLoadApplicationSpecificSettings_WhenApplicationNameIsEmpty()
{
using TempDirectory tempDir = new();
string appSettingsPath = Path.Combine(tempDir.Path, ".settings.json");

// Create test configuration file that should NOT be loaded
File.WriteAllText(appSettingsPath, """{"TestKey": "ShouldNotBeLoaded"}""");

using var host = new HostBuilder()
.ConfigureDefaults(args: null)
.UseContentRoot(tempDir.Path)
.ConfigureHostConfiguration(config =>
{
config.AddInMemoryCollection(new[]
{
new KeyValuePair<string, string>(HostDefaults.ApplicationKey, ""),
new KeyValuePair<string, string>(HostDefaults.EnvironmentKey, "Production")
});
})
.Build();

var configuration = host.Services.GetRequiredService<IConfiguration>();

// Verify that app-specific settings are not loaded when ApplicationName is empty
Assert.Null(configuration["TestKey"]);
}

[Fact]
public void ConfigureDefaults_ReplacesPathSeparatorsInApplicationName()
{
using TempDirectory tempDir = new();
string appSettingsPath = Path.Combine(tempDir.Path, "my_app.settings.json");

// Create test configuration file with path separators replaced by underscores
File.WriteAllText(appSettingsPath, """{"TestKey": "PathSeparatorValue"}""");

using var host = new HostBuilder()
.ConfigureDefaults(args: null)
.UseContentRoot(tempDir.Path)
.ConfigureHostConfiguration(config =>
{
config.AddInMemoryCollection(new[]
{
new KeyValuePair<string, string>(HostDefaults.ApplicationKey, "my/app"),
new KeyValuePair<string, string>(HostDefaults.EnvironmentKey, "Production")
});
})
.Build();

var configuration = host.Services.GetRequiredService<IConfiguration>();
var hostEnvironment = host.Services.GetRequiredService<IHostEnvironment>();

// Verify that ApplicationName retains original value (not sanitized)
Assert.Equal("my/app", hostEnvironment.ApplicationName);

// Verify that path separators are replaced with underscores for file loading
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment could be better, e.g.:

Suggested change
// Verify that path separators are replaced with underscores for file loading
// Verify the value from the application specific settings file with the sanitized name is loaded

Assert.Equal("PathSeparatorValue", configuration["TestKey"]);
}

[Fact]
public void ConfigureDefaults_ApplicationSpecificSettingsOverrideAppSettings()
{
using TempDirectory tempDir = new();
string appSettingsPath = Path.Combine(tempDir.Path, "appsettings.json");
string appSpecificSettingsPath = Path.Combine(tempDir.Path, "myapp.settings.json");

// Create test configuration files
File.WriteAllText(appSettingsPath, """{"SharedKey": "AppSettingsValue", "AppKey": "AppSettingsOnly"}""");
File.WriteAllText(appSpecificSettingsPath, """{"SharedKey": "AppSpecificValue", "SpecificKey": "AppSpecificOnly"}""");

using var host = new HostBuilder()
.ConfigureDefaults(args: null)
.UseContentRoot(tempDir.Path)
.ConfigureHostConfiguration(config =>
{
config.AddInMemoryCollection(new[]
{
new KeyValuePair<string, string>(HostDefaults.ApplicationKey, "myapp"),
new KeyValuePair<string, string>(HostDefaults.EnvironmentKey, "Development")
});
})
.Build();

var configuration = host.Services.GetRequiredService<IConfiguration>();

// Verify that app-specific settings override general appsettings
Assert.Equal("AppSpecificValue", configuration["SharedKey"]);
Assert.Equal("AppSettingsOnly", configuration["AppKey"]);
Assert.Equal("AppSpecificOnly", configuration["SpecificKey"]);
}

internal class ServiceD { }

internal class ServiceA { }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
</PropertyGroup>

<ItemGroup>
<Compile Include="$(CommonTestPath)System\IO\TempDirectory.cs" Link="Common\System\IO\TempDirectory.cs" />
<Content Include="testroot\**\*" CopyToOutputDirectory="PreserveNewest" />
<Content Include="appSettings.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
Expand Down
Loading