A Setting Is a Type I Can Load, Not a String I Hope Exists
Business configuration such as a gateway URL, a dispatch radius, or an API key should compile as a property, carry its own validation, and stay encrypted at rest. I build it as a typed settings module.
A payment adapter needs a base URL, a charge path, a timeout, and an API key. If those values live behind configuration["Payments:Secret"], the compiler cannot tell you the section was renamed. You find out at the first real charge, when the HTTP client gets a null. Worse, the key is a plain string that any log line can print.
I have built the same answer into two very different .NET systems: a microservices payments backend and a modular delivery platform on ABP. In both, business configuration is a class. Code loads it by type, operations edit it in an admin screen, and secrets never travel as plain strings.
This article is for .NET engineers who have outgrown appsettings.json for values that operations, not developers, need to change. By the end you should be able to judge whether a typed settings module is worth adding to your host.
A string key compiles even when the adapter is wrong
IConfiguration is the right tool for bootstrap values: connection strings, logging, the address of the settings store itself. It is the wrong tool for business values that change without a deploy.
String keys fail in three quiet ways:
- A renamed key returns
nullinstead of a compile error. - Every caller parses its own
intordecimal, with its own default. - A secret and a harmless label look the same, so both get logged.
The Options pattern already fixes the first two for values that ship with a deploy. IOptions<T> with ValidateDataAnnotations() and ValidateOnStart() gives you a typed class that fails the host on boot when a value is wrong. I use it for bootstrap configuration. What it does not give you is a value that operations change in an admin screen at runtime, with a permission check, an audit trail, encryption at rest, and no restart or file edit. IOptionsMonitor<T> can reload, but the source is still a file, environment variables, or a configuration provider a developer manages.
The fix is to keep what the Options pattern gets right, a class the compiler checks, and move the values into a store that operations own.
The class is the schema
A settings group is a plain class. Properties are the keys. Defaults are the seed. Attributes carry validation and sensitivity.
[ConfigGroup("CardGateway")]
public sealed class CardGatewaySettings : IAppConfig
{
[Required, Url]
public string BaseUrl { get; set; } = "";
public string ChargePath { get; set; } = "/v1/charges";
[Range(1, 60)]
public int TimeoutSeconds { get; set; } = 15;
[Secret]
public string ApiKey { get; set; } = "";
}
The adapter asks for the type and gets a validated object back. No section names, no TryParse. Every value it needs, the address, the timeout, and the key, comes from that one object.
public async Task<ChargeResult> ChargeAsync(ChargeRequest request, CancellationToken ct)
{
var gateway = await settings.GetAsync<CardGatewaySettings>(ct);
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(gateway.TimeoutSeconds));
// Trim and join by hand: new Uri(base, "/v1/charges") would drop any path in BaseUrl.
var url = $"{gateway.BaseUrl.TrimEnd('/')}/{gateway.ChargePath.TrimStart('/')}";
using var message = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = JsonContent.Create(request)
};
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", gateway.ApiKey);
using var response = await http.SendAsync(message, timeout.Token);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<ChargeResult>(timeout.Token)
?? throw new InvalidOperationException("Empty charge response.");
}
Adding a new provider means adding a class. The admin screen already knows how to list a group, show its keys, and mask a sensitive value.
One group per type, one row per property
The store maps a type to a group name and each property to a row: group, key, value, data type, and an encrypted flag. Where one table serves several environments, an environment column keeps staging and production values apart.
Sensitive properties are encrypted before they reach the row, and they stay encrypted in the cache. A dumped cache key is not a password dump. Decryption happens in one place, on the way into the typed object.
Seed the holes, keep what operations changed
Every deploy registers the seed for each group. The rule is narrow: create rows that do not exist yet, and never touch rows that do. A deploy that adds an alert delay must not reset a courier cap that operations tuned last week.
public async Task<T> SeedMissingAsync<T>(T seed, CancellationToken ct)
where T : class, IAppConfig, new()
{
var group = ConfigGroup.Of<T>();
await using var groupLock = await locks.AcquireAsync($"settings:{group.Name}", ct);
var stored = await rows.ReadGroupAsync(group.Name, ct);
foreach (var property in group.Properties.Where(p => !stored.ContainsKey(p.Name)))
{
await rows.InsertAsync(group.CreateRow(property, property.GetValue(seed), protector), ct);
}
return await GetAsync<T>(ct);
}
The lock matters because several instances start at once. Each one would otherwise see the same missing row and insert it. I back the lock with a unique index on group and key, so a second writer fails loudly instead of creating a duplicate.
Validate the whole object before any row moves
Writes go through one method. It validates the full object, checks a concurrency stamp, encrypts sensitive fields, writes the rows, and clears the cache only after the transaction commits.
public async Task SaveAsync<T>(T value, string expectedStamp, CancellationToken ct)
where T : class, IAppConfig, new()
{
Validator.ValidateObject(value, new ValidationContext(value), validateAllProperties: true);
var group = ConfigGroup.Of<T>();
var stored = await rows.LockGroupAsync(group.Name, ct);
if (stored.Stamp != expectedStamp)
throw new ConfigConflictException(group.Name);
await rows.WriteAsync(group.ToRows(value, protector), ct);
unitOfWork.OnCompleted(() => cache.RemoveAsync(group.Name));
}
Three decisions sit in those lines:
- Validate the object, not the field. A dispatch radius and a max distance can be valid alone and wrong together. The group implements
IValidatableObjectfor those cross-field rules, andValidator.ValidateObjectruns them after the attribute checks pass. - Optimistic concurrency per group. Two admins editing the same group cannot silently overwrite each other.
- Invalidate after commit. Clearing the cache before the commit lets another request reload the old values and cache them again.
On the ABP platform this method is a domain service. The edit permission is checked at the application boundary, so the domain stays free of HTTP concerns. HTTP tests lock the behavior: an invalid value gets a 400, a stale stamp gets a 409, and a caller without the permission gets a 403.
Where I draw the line
A typed settings module is not everything configuration needs. I keep it out of some jobs on purpose, and I hold it to a few rules:
- Bootstrap configuration stays outside. Connection strings and the encryption key belong in environment configuration or a secret store. The key that protects settings must not live in the same database backup as the settings.
- Feature flags are a different tool. Gradual rollout, targeting, and kill switches need a flag service. A settings row has no audience.
- The environment should be explicit. The value that decides which credentials load should be configured and validated at startup, not parsed out of a host or environment name.
- An empty string is a value. If a URL may be blank, validation should say so. The store should save it, not skip it.
What I carry into the next .NET host
I carry the contract, not the files:
- A marker interface and a group attribute.
- One group per type, one row per property.
- A sensitivity attribute that encrypts at rest and in cache.
- Seed that fills holes under a lock and a unique index.
- One save path: validate, compare stamp, write, invalidate after commit.
In a microservices host the contract is a shared settings service each service registers. In an ABP host it is a domain service plus a permission per group. The next payment adapter is another class, and the compiler already knows its shape.