7.8 — Options Validation and ValidateOnStart¶
← Roadmap · Section: 7. Configuration and Options Prev: 7.7 Binding to POCOs · Next: 7.9 Reload on change
Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
Options validation checks that a bound configuration class actually holds sensible values,
and ValidateOnStart() makes that check run at application startup rather than at first use.
- Without it, a missing setting is silent — binding leaves the default and you find out much later.
- Three levels: DataAnnotations attributes, a
Validatelambda, or a fullIValidateOptions<T>class. - ⚠️ Validation is lazy by default.
ValidateOnStart()is the part that actually matters.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Options validation | a feature | Checking a bound options object is valid before anything uses it. |
AddOptions<T>() |
a method | Starts a fluent builder for configuring, binding and validating T. |
ValidateDataAnnotations() |
a method | Validates [Required], [Range] and similar attributes on the class. |
Validate(...) |
a method | Registers a lambda returning bool, with a failure message. |
IValidateOptions<T> |
an interface | A full validation class. For anything needing dependencies or complex rules. |
ValidateOnStart() |
a method | Runs validation at startup instead of first access. |
OptionsValidationException |
an exception | Thrown when validation fails, listing every failure. |
| Lazy validation | the default behaviour | Validation runs the first time .Value is read, not at startup. |
| Fail fast | a principle | Detect a misconfiguration at boot, before the app serves traffic. |
ValidateComplexMembers |
a DataAnnotations option (.NET 8+) | Validates nested options objects too. |
The concept¶
The problem: binding is silent¶
From 7.7: if a configuration key is missing, the property keeps its default. No error, no warning.
public class PaymentOptions
{
public string ApiKey { get; set; } = ""; // key missing → stays ""
public int TimeoutSeconds { get; set; } // key missing → stays 0
}
An application configured like that starts perfectly. Then:
- The first payment fails with a 401 from Stripe, because the API key is empty
- Or worse,
TimeoutSeconds = 0means every HTTP call times out instantly
And the error happens at the worst possible moment — during a customer transaction, hours after deployment, with a message that points at Stripe rather than at your configuration.
Validation moves that failure to application startup, where it fails the deployment and never receives traffic.
A picture: a pre-flight check versus discovering the fuel gauge is broken at 30,000 feet. Both find the problem. Only one of them is survivable.
⚠️ The part people miss¶
Validation on its own is lazy — it runs when someone first reads .Value:
builder.Services
.AddOptions<PaymentOptions>()
.Bind(builder.Configuration.GetSection("Payments"))
.ValidateDataAnnotations(); // ⚠️ runs on first ACCESS, not at startup
So the application still starts with broken configuration. The failure just moves from "Stripe returns 401" to "an exception on the first request that touches payments" — better, but still in production, still during a customer transaction.
ValidateOnStart() is the line that makes this worth doing:
Now the deployment fails, the orchestrator does not route traffic to it, and the previous version keeps running. That is the whole value.
How it works¶
The simple version — DataAnnotations¶
public class PaymentOptions
{
public const string SectionName = "Payments";
[Required(AllowEmptyStrings = false)]
[Url]
public string BaseUrl { get; set; } = "";
[Required(AllowEmptyStrings = false)]
[MinLength(20)]
public string ApiKey { get; set; } = "";
[Range(1, 300)]
public int TimeoutSeconds { get; set; } = 30;
[Range(0, 10)]
public int MaxRetries { get; set; } = 3;
}
builder.Services
.AddOptions<PaymentOptions>()
.Bind(builder.Configuration.GetSection(PaymentOptions.SectionName))
.ValidateDataAnnotations()
.ValidateOnStart();
Missing the API key now produces this at startup:
OptionsValidationException: DataAnnotation validation failed for 'PaymentOptions' members:
'ApiKey' with the error: 'The ApiKey field is required.'.
⚠️ [Required] on a string with a default of "" needs AllowEmptyStrings = false. By
default [Required] treats an empty string as present, so the check passes and you are back to
silence. That catches people out constantly.
⚠️ And [Required] on a value type is useless. An int is never null, so a missing key
gives you 0 and [Required] is satisfied. Use [Range] with a sensible minimum instead:
That is the more important of the two, because a zero timeout or a zero batch size fails in confusing ways.
The Validate lambda — for rules attributes cannot express¶
builder.Services
.AddOptions<PaymentOptions>()
.Bind(builder.Configuration.GetSection(PaymentOptions.SectionName))
.ValidateDataAnnotations()
.Validate(o => o.MaxRetries * o.TimeoutSeconds <= 300,
"MaxRetries multiplied by TimeoutSeconds must not exceed 300 seconds total.")
.Validate(o => !o.ApiKey.StartsWith("sk_test_") || o.AllowTestKeys,
"A test API key is configured but AllowTestKeys is false.")
.ValidateOnStart();
Each Validate takes a predicate and a message. Chain as many as you need.
That second rule is the kind of check worth writing. A test key in production is a real incident, and it is exactly the sort of thing nobody notices until money does not move.
⚠️ The lambda has no access to DI, so it cannot check anything requiring a service. For that you need the full interface.
How it actually works — IValidateOptions<T>¶
When validation needs dependencies or produces several failures:
public class PaymentOptionsValidator(IHostEnvironment env) : IValidateOptions<PaymentOptions>
{
public ValidateOptionsResult Validate(string? name, PaymentOptions options)
{
var failures = new List<string>();
if (string.IsNullOrWhiteSpace(options.ApiKey))
failures.Add("Payments:ApiKey is required.");
if (env.IsProduction() && options.ApiKey.StartsWith("sk_test_"))
failures.Add("A test API key must not be used in Production.");
if (options.TimeoutSeconds is < 1 or > 300)
failures.Add($"Payments:TimeoutSeconds must be 1-300, but was {options.TimeoutSeconds}.");
return failures.Count > 0
? ValidateOptionsResult.Fail(failures) // ALL failures, not just the first
: ValidateOptionsResult.Success;
}
}
builder.Services.AddSingleton<IValidateOptions<PaymentOptions>, PaymentOptionsValidator>();
builder.Services
.AddOptions<PaymentOptions>()
.Bind(builder.Configuration.GetSection(PaymentOptions.SectionName))
.ValidateOnStart();
Two advantages over the lambda: it can take dependencies through DI — IHostEnvironment here, so
the rule differs by environment — and it can report every failure at once rather than stopping
at the first.
Reporting all failures matters. Fixing configuration one error per deployment cycle is miserable; seeing all four at once takes one iteration.
The deeper detail — nested options¶
⚠️ By default, DataAnnotations validation does not recurse into nested objects:
public class PaymentOptions
{
[Required] public string ApiKey { get; set; } = "";
public StripeOptions Stripe { get; set; } = new(); // ⚠️ NOT validated
}
public class StripeOptions
{
[Required] public string WebhookSecret { get; set; } = ""; // never checked
}
.NET 8 added an option for it:
builder.Services
.AddOptions<PaymentOptions>()
.Bind(builder.Configuration.GetSection("Payments"))
.ValidateDataAnnotations()
.Validate(o => !string.IsNullOrWhiteSpace(o.Stripe.WebhookSecret),
"Payments:Stripe:WebhookSecret is required.") // explicit, works everywhere
.ValidateOnStart();
Or use [ValidateObjectMembers] from the options validation source generator. The explicit
Validate call is the most portable answer, and it is clearer about what is being checked.
What ValidateOnStart actually does¶
It registers an IHostedService that resolves the options during startup
(4.5). Resolving triggers binding and
validation, and a failure throws before the server starts listening.
⚠️ Because it runs in StartAsync, it blocks startup — which is exactly what you want, but it
means the failure appears in your startup logs rather than as an HTTP error. Make sure your
logging is configured to capture startup output, or a failed deployment looks like a container
that exited with no explanation.
Adding a top-level try/catch helps (4.6):
try
{
app.Run();
}
catch (OptionsValidationException ex)
{
Log.Fatal("Configuration is invalid:\n{Failures}", string.Join("\n", ex.Failures));
throw;
}
finally
{
Log.CloseAndFlush(); // ensure the message is written before the process dies
}
Code¶
The complete pattern, as it would appear in a real application:
public class PaymentOptions
{
public const string SectionName = "Payments";
[Required(AllowEmptyStrings = false), Url]
public string BaseUrl { get; set; } = "";
[Required(AllowEmptyStrings = false), MinLength(20)]
public string ApiKey { get; set; } = "";
[Range(1, 300)]
public int TimeoutSeconds { get; set; } = 30;
[Range(0, 10)]
public int MaxRetries { get; set; } = 3;
public bool AllowTestKeys { get; set; }
public StripeOptions Stripe { get; set; } = new();
}
// A registration extension keeps Program.cs readable — see 4.3
public static class PaymentModuleExtensions
{
public static IServiceCollection AddPaymentModule(
this IServiceCollection services, IConfiguration config)
{
services
.AddOptions<PaymentOptions>()
.Bind(config.GetSection(PaymentOptions.SectionName))
.ValidateDataAnnotations()
.Validate(o => !string.IsNullOrWhiteSpace(o.Stripe.WebhookSecret),
"Payments:Stripe:WebhookSecret is required.")
.Validate(o => o.MaxRetries * o.TimeoutSeconds <= 300,
"MaxRetries × TimeoutSeconds must not exceed 300 seconds.")
.ValidateOnStart();
// Environment-dependent rules need DI, so they go in a validator class
services.AddSingleton<IValidateOptions<PaymentOptions>, PaymentOptionsValidator>();
services.AddScoped<IPaymentService, PaymentService>();
return services;
}
}
// The service can now trust its options completely
public class PaymentService(IOptions<PaymentOptions> options, IHttpClientFactory factory)
{
private readonly PaymentOptions _options = options.Value;
// No null checks, no defensive defaults, no "if the API key is missing" branch.
// Validation guaranteed all of that at startup.
}
That last comment is the real payoff. Validated options mean services stop defending against misconfiguration, which removes a whole layer of defensive code.
Interview questions¶
Q: Why do you need options validation?
Because binding is silent. If a configuration key is missing, the property keeps its default — an empty API key, or a timeout of zero — and the application starts perfectly. The failure then happens at the worst moment, during a real transaction, with an error that points at the downstream service rather than at your configuration. Validation moves that to startup, where a misconfigured deployment fails and never receives traffic.
Q: What does ValidateOnStart add?
It is the part that actually matters. Validation on its own is lazy — it runs the first time
someone reads .Value, so the application still starts with broken configuration and fails later
on some request. ValidateOnStart registers a hosted service that resolves the options during
startup, so binding and validation happen before the server listens. A failure then aborts the
boot, the orchestrator does not route traffic to the new instance, and the previous version keeps
running.
Q: What are the ways to validate options?
Three levels. DataAnnotations attributes on the class with ValidateDataAnnotations, which
covers Required, Range and similar. A Validate lambda with a message, for rules that span
several properties. And an IValidateOptions<T> implementation for anything needing
dependencies — checking that a test API key is not being used in Production requires
IHostEnvironment, which the lambda cannot access. The interface also lets you report every
failure at once instead of stopping at the first, which saves fixing configuration one error per
deployment.
Q: What are the traps with DataAnnotations on options?
Two that catch people. [Required] on a string treats an empty string as present by default, and
since a missing key leaves the property at its "" initialiser, the check passes — you need
AllowEmptyStrings = false. And [Required] on a value type is meaningless, because an int is
never null, so a missing key gives you zero and validation is satisfied. For numbers you want a
[Range] with a sensible minimum, which catches the zero. There is also the fact that nested
options objects are not validated by default.
Traps ⚠️¶
- Validation is lazy without
ValidateOnStart(). The app starts broken and fails later. [Required]on a string accepts empty strings unless you setAllowEmptyStrings = false.[Required]on a value type does nothing. A missing key gives 0, which is "present". Use[Range].- Nested options objects are not validated by default.
- The
Validatelambda cannot use DI. Environment-dependent rules needIValidateOptions<T>. - DataAnnotations stops at the first failure per property, so returning all failures needs the validator interface.
- Startup failures appear in startup logs, not as HTTP errors — configure logging to capture them, and flush before exit.
- Validation runs per named option, so named options each need validating.
Related¶
- 7.7 Binding to POCOs — why binding is silent
- 7.6 The options pattern — the interfaces being validated
- 7.4 Secret providers — failing fast on a missing secret
- 4.6 Application lifecycle — catching startup failures
- 4.5 Host interfaces — how
ValidateOnStartworks - 11.4 DataAnnotations — the same attributes for request models
- 1.6 required — why the keyword does not help here