Last active
April 11, 2025 11:04
-
-
Save davidfowl/256525d319129df973839cd7245a1f87 to your computer and use it in GitHub Desktop.
Allows specifying default configuration values in code while still allowing other sources to override
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Extensions.Configuration.Memory; | |
var builder = WebApplication.CreateBuilder(args); | |
builder.Configuration.AddConfigurationDefaults(new() | |
{ | |
{ "request:timeout", "60" } | |
}); | |
var app = builder.Build(); | |
// Show example of manually binding from configuration | |
var config = new Config(); | |
app.Configuration.GetSection("request").Bind(config); | |
app.MapGet("/", () => config.Timeout); | |
app.Run(); | |
class Config | |
{ | |
public int Timeout { get; set; } | |
} | |
public static class ConfigurationExtensions | |
{ | |
public static IConfigurationBuilder AddConfigurationDefaults(this IConfigurationBuilder configurationBuilder, Dictionary<string, string?> defaults) | |
{ | |
// Insert at 0 so that other configuraton sources can override the defaults | |
configurationBuilder.Sources.Insert(0, new MemoryConfigurationSource() | |
{ | |
InitialData = defaults | |
}); | |
return configurationBuilder; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment