Configuration: Advanced
Advanced configuration topics including startup validation, builder API reference, and complete configuration patterns.
Before You Start
- Completed Configuration basics
- Familiarity with Microsoft.Extensions.Options
Configuration Validation
Validate configuration at startup:
builder.Services.AddOptions<DispatchOptions>()
.Bind(builder.Configuration.GetSection("Dispatch"))
.Validate(options =>
{
if (options.DefaultTimeout <= TimeSpan.Zero)
return false;
return true;
}, "DefaultTimeout must be positive")
.ValidateOnStart();
Builder Pattern Reference
IDispatchBuilder -- Core Methods
| Method | Purpose | Example |
|---|---|---|
ConfigurePipeline() | Named pipeline setup | dispatch.ConfigurePipeline("default", p => ...) |
RegisterProfile() | Pipeline profile | dispatch.RegisterProfile(new MyProfile()) |
AddBinding() | Transport binding | dispatch.AddBinding(b => ...) |
UseMiddleware<T>() | Global middleware | dispatch.UseMiddleware<LoggingMiddleware>() |
ConfigureOptions<T>() | Options configuration | dispatch.ConfigureOptions<DispatchOptions>(o => ...) |
IDispatchBuilder -- Transport Extensions (Use prefix)
| Method | Package | Example |
|---|---|---|
UseRabbitMQ() | Excalibur.Dispatch.Transport.RabbitMQ | dispatch.UseRabbitMQ(rmq => ...) |
UseKafka() | Excalibur.Dispatch.Transport.Kafka | dispatch.UseKafka(kafka => ...) |
UseAwsSqs() | Excalibur.Dispatch.Transport.AwsSqs | dispatch.UseAwsSqs(sqs => ...) |
UseAzureServiceBus() | Excalibur.Dispatch.Transport.AzureServiceBus | dispatch.UseAzureServiceBus(asb => ...) |
UseGooglePubSub() | Excalibur.Dispatch.Transport.GooglePubSub | dispatch.UseGooglePubSub(pubsub => ...) |
All transport methods support named overloads: dispatch.UseKafka("analytics", kafka => ...).
IDispatchBuilder -- Cross-Cutting Extensions (Use prefix)
| Method | Package | Example |
|---|---|---|
UseObservability() | Excalibur.Dispatch.Observability | dispatch.UseObservability(obs => ...) |
UseResilience() | Excalibur.Dispatch.Resilience.Polly | dispatch.UseResilience() |
UseCaching() | Excalibur.Dispatch.Caching | dispatch.UseCaching() |
UseSecurity() | Excalibur.Security | dispatch.UseSecurity(configuration) |
Standalone IServiceCollection Methods
These standalone methods remain available for consumers who prefer direct registration:
| Method | Purpose | Package |
|---|---|---|
AddDispatch() | Core Dispatch services | Excalibur.Dispatch |
AddRabbitMQTransport() | RabbitMQ transport | Excalibur.Dispatch.Transport.RabbitMQ |
AddKafkaTransport() | Kafka transport | Excalibur.Dispatch.Transport.Kafka |
AddAwsSqsTransport() | AWS SQS transport | Excalibur.Dispatch.Transport.AwsSqs |
AddAzureServiceBusTransport() | Azure Service Bus | Excalibur.Dispatch.Transport.AzureServiceBus |
AddGooglePubSubTransport() | Google Pub/Sub | Excalibur.Dispatch.Transport.GooglePubSub |
AddDispatchObservability() | Observability | Excalibur.Dispatch.Observability |
AddDispatchResilience() | Resilience (Polly) | Excalibur.Dispatch.Resilience.Polly |
UseCaching() | Caching (on IDispatchBuilder) | Excalibur.Dispatch.Caching |
UseSecurity() | Security (on IDispatchBuilder) | Excalibur.Security |
AddMessagePackSerializer() | MessagePack serialization | Excalibur.Dispatch.Serialization.MessagePack |
AddMemoryPackSerializer() | MemoryPack serialization | Excalibur.Dispatch.Serialization.MemoryPack |
Common Configuration Patterns
Minimal API
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDispatch(dispatch =>
{
dispatch.AddHandlersFromAssembly(typeof(Program).Assembly);
});
var app = builder.Build();
app.MapPost("/orders", async (CreateOrderAction action, IDispatcher dispatcher, CancellationToken ct) =>
await dispatcher.DispatchAsync(action, ct));
app.Run();
Full-Featured Setup
using Excalibur.Dispatch;
using Excalibur.Dispatch.Middleware.Auth;
using Excalibur.Dispatch.Middleware.Logging;
using Excalibur.Dispatch.Middleware.Validation;
using Excalibur.Dispatch.Options.Configuration;
using Excalibur.Dispatch.Observability.Metrics;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using OpenTelemetry.Trace;
using OpenTelemetry.Metrics;
public static class FullDispatchSetup
{
public static void Run(string[] args, System.Reflection.Assembly handlerAssembly)
{
var builder = WebApplication.CreateBuilder(args);
var kafkaServers = builder.Configuration["Kafka:Servers"]
?? throw new InvalidOperationException("Kafka:Servers is required.");
// Unified Dispatch registration -- transports + cross-cutting through the builder
builder.Services.AddDispatch(dispatch =>
{
dispatch.AddHandlersFromAssembly(handlerAssembly);
// Transports (Use prefix)
dispatch.UseKafka(kafka => kafka.BootstrapServers(kafkaServers));
dispatch.UseRabbitMQ(rmq => rmq.HostName("localhost"));
// Cross-cutting concerns (Use prefix)
dispatch.UseObservability();
dispatch.UseResilience(); // Registers adapters; execute a configured policy at the dependency boundary.
dispatch.UseCaching();
dispatch.UseSecurity(builder.Configuration);
// Global middleware
dispatch.UseMiddleware<LoggingMiddleware>();
dispatch.UseMiddleware<ValidationMiddleware>();
dispatch.UseMiddleware<AuthorizationMiddleware>();
// Options
dispatch.ConfigureOptions<DispatchOptions>(options =>
{
options.DefaultTimeout = TimeSpan.FromSeconds(30);
});
// Multi-transport routing
dispatch.UseRouting(routing =>
{
routing.Transport
.Route<OrderCreatedEvent>().To("kafka")
.Default("rabbitmq");
});
});
// Serialization
// JSON is the default with AddDispatch(). For binary serializers, install the provider package:
// Health checks
builder.Services.AddHealthChecks()
.AddTransportHealthChecks();
// OpenTelemetry
builder.Services.AddOpenTelemetry()
.WithTracing(t => t.AddSource("Excalibur.Dispatch"))
.WithMetrics(m => m.AddDispatchMetrics());
var app = builder.Build();
app.MapHealthChecks("/health");
app.Run();
}
}
public sealed record OrderCreatedEvent(Guid OrderId) : IIntegrationEvent;
Combined with Excalibur
When using Excalibur subsystems alongside Dispatch, call AddDispatch for transport and pipeline configuration, then AddExcalibur for domain infrastructure. AddExcalibur registers Dispatch primitives with defaults, so both orderings are safe:
// Dispatch -- transports, middleware, pipelines
builder.Services.AddDispatch(dispatch =>
{
dispatch.AddHandlersFromAssembly(typeof(Program).Assembly);
dispatch.UseKafka(kafka => kafka.BootstrapServers("localhost:9092"));
dispatch.UseObservability();
dispatch.ConfigurePipeline("default", p => p.UseValidation());
});
// Excalibur -- event sourcing, outbox, sagas
builder.Services.AddExcalibur(excalibur =>
{
excalibur
.AddEventSourcing(es => es.UseEventStore<SqlServerEventStore>())
.AddOutbox(outbox => outbox.UseSqlServer(opts => opts.ConnectionString(connectionString)))
.AddSagas();
});
Options Validation with ValidateOnStart
Excalibur uses ValidateOnStart() to catch configuration errors at application startup rather than at first use. This follows the Microsoft.Extensions.Options validation pattern.
How It Works
When you call ValidateOnStart(), the framework validates all IOptions<T> registrations during IHost.StartAsync(). If any validation fails, the application throws OptionsValidationException immediately -- before handling any requests.
// This is what happens inside Excalibur's DI extensions:
services.AddOptions<LeaderElectionOptions>()
.ValidateDataAnnotations() // Validates [Required], [Range], etc.
.ValidateOnStart(); // Runs validation at startup, not first use
Advertised capabilities are wired or fail loud
Excalibur holds a structural invariant: any configuration option the API advertises is either backed by a live implementation, or it fails fast at startup with a clear OptionsValidationException. A configured strategy or capability never silently degrades to a no-op at runtime.
In practice this means:
-
Selecting a strategy or provider that the active package cannot service is rejected during
IHost.StartAsync(), not ignored on the hot path. -
Provider registration paths fail fast on invalid options. For example, every serverless-hosting registration overload (
AddServerlessHosting(...)) wiresValidateOnStart(), so misconfiguration surfaces at startup regardless of which overload you call. -
A capability that a given store does not implement (for example, retry-backoff scheduling on a store that lacks it) falls back to the documented default behavior rather than throwing — fail-open for optional cross-cutting features, fail-loud for advertised configuration.
-
Durability prerequisites are checked at startup. Wiring a production host with a volatile (in-memory) audit, grant, key, or schedule store is rejected at startup — a volatile store would report every write as saved and then lose it on restart, which is exactly the failure a fail-fast gate exists to prevent. Each subsystem exposes an explicit opt-out for development and test hosts (
AuditLoggingOptions.AllowVolatileAuditStore,GrantDurabilityOptions.AllowVolatileGrantStore,KeyDurabilityOptions.AllowVolatileKeyProvider,ScheduleDurabilityOptions.AllowVolatileScheduleStore); the default is the protective value you get by saying nothing. These gates run from host startup — a host-less container must callValidateStartupGates()to trigger them.Where the schedule-store gate applies. It is installed by the compositions that start the scheduler runtime —
AddTimeAwareScheduling,AddAdaptiveTimeAwareScheduling,AddLightweightTimeAwareSchedulingandAddThroughputTimeAwareScheduling— and not byAddDispatchSchedulingon its own. That split is deliberate. Running the scheduler is what turns a schedule from a request into a promise: the host accepts a delivery now and owes it later, and a volatile store breaks that promise on restart after having reported the schedule accepted, so the failure appears only as an absence. A host that composes scheduling without ever starting the runtime — a development host, or one replacing an in-process mediator — is not made to justify a store it never schedules against. Register a durable store withAddDurableScheduleStore<T>(), which replaces the in-memory registration in either composition order. This registration declares the custom provider's durability; the gate does not verify its persistence or recovery after process termination. Verify those guarantees against the provider's actual storage.
Scheduler clock and deadlines
The scheduler uses its injected TimeProvider for due-time reads, polling waits, and operation deadlines. Without an explicit clock, it uses TimeProvider.System. Tests can supply a controllable clock and advance it to exercise these boundaries without waiting for wall time.
An active finite deadline starts when the operation begins. A zero deadline is already expired when its cancellation scope is created; an infinite deadline or inactive timeout policy creates no deadline timer. Caller cancellation remains effective in every mode. Deadline resources are disposed after the operation settles.
A schedule-change signal can wake polling early. Expiring the polling deadline cancels the pending signal read before the next wait begins, so an abandoned read cannot consume a later notification. When host cancellation is observed, the scheduler stops instead of treating cancellation as another polling wake.
These clock semantics do not establish durable storage or exactly-once delivery. The schedule-store durability gate still applies. Persisting schedules across a process restart requires a durable store; replacing a dependency-injection container around an in-memory store does not provide that guarantee.
Recurring job model migration
RecurringCronJob has been withdrawn; constructing that model never registered work or configured the worker. Use the existing IDispatchScheduler.ScheduleRecurringAsync overloads below with the actual message, installed timezone and explicit CronRecurrenceProfile where required. These are the active recurring APIs; no working recurrence feature was removed.
For a production hosted scheduler, provision the SQL schedule scripts in SQL Server schedule storage, register that selected store, and start the existing time-aware runtime. SchedulerOptions.MaxAdmissionAttemptsPerOccurrence defaults to 5. It is a host-requested policy captured per occurrence by the store and counts admissions, including abandoned or ambiguously settled grants—not just failed handler calls. It is not the removed model's MaxRetryAttempts = 3, nor a new per-job retry policy. An unsettled failed occurrence remains retryable under that budget; exhaustion attempts quarantine without discarding its provenance. Use the existing bounded failure queries and expected-token recovery on that same selected store, described below. Recovery command IDs must be retained and reused when reconciling an uncertain response.
The removed model's name, tags, priority, start/end windows and cumulative statistics were caller-owned values, not enforced scheduling behavior. Preserve any useful application catalog data in your application; do not assume it was migrated into a runtime policy. Existing schedule metadata and per-occurrence failure snapshots remain available. Handler side effects remain at-least-once; a retry policy registered with Polly does not replace the durable occurrence admission protocol.
Scheduler admission and cancellation
The public schedule-store interfaces and their message, lease and completion data types
are defined in Excalibur.Dispatch.Abstractions, under the
Excalibur.Dispatch.Delivery namespace. Provider contracts can reference that assembly;
the scheduler workers and runtime registration remain in Excalibur.Dispatch.
The worker uses IScheduleExecutionStore when the configured IScheduleStore implements
that optional capability. Do not register a separate execution store: administration and
execution must operate on the same backing authority. The in-memory store supports this
capability within one process and remains volatile.
Each execution is admitted against its exact stored occurrence and administrative generation before decoding or dispatch. Cancellation or replacement that wins admission prevents the invocation. Work already admitted may finish, but its stale progress cannot reactivate cancellation or overwrite a replacement. One admission permits one successful progress commit. Shutdown releases ownership without advancing the retained occurrence. Handlers must tolerate another attempt after an interrupted or ambiguously completed execution.
For late recurring schedules, SkipMissed skips catch-up, ExecuteLatestMissed coalesces
to one invocation, and DisableSchedule disables the schedule. ExecuteAllMissed processes
at most MaxMissedExecutions per poll, retaining further occurrences for subsequent polls.
Zero skips missed catch-up and advances to a future occurrence; on-time and overdue
one-time deliveries remain eligible. Ordinary interval schedules advance from completion,
whereas replay advances from each persisted occurrence.
An undecodable or failed invocation retains its admitted occurrence and consumed
admission count. Its captured automatic budget cannot be widened by later host options.
Previously admitted unsettled work is not skipped by catch-up policy. At exhaustion the
worker stops invoking the handler and attempts quarantine. Confirmed quarantine disables
the schedule and retains its provenance. Failed or uncertain disposition writes remain
unresolved and report degraded health until reconciled; they are not confirmed quarantine.
Healthy schedules remain eligible.
Counts describe authority grants, including abandoned grants, not proven handler calls.
Handler side effects remain at-least-once. Host shutdown retains due work. An expired processing deadline is
honored even if a handler swallows its cancellation and returns success.
A provider exposing only IScheduleStore can be composed for administration, but cannot
start the preserving scheduler runtime. The selected store must implement
IScheduleExecutionFailureStore, including atomic admission, captured budgets, retained
failure/quarantine and expected-token recovery. Test the administrative and execution
contracts with their conformance kits and the failure capability with
ScheduleFailureStoreConformanceTestKit; wire every applicable arm. Cleanup must target the same
backing authority used by each test. These controls do not establish durable restart,
crashed-owner recovery, distributed external-effect fencing or NativeAOT compatibility;
verify those against the actual provider and application.
Explicit cron timezone transitions
Choose the supported immutable declaration when scheduling in a transition-capable zone:
using System.Diagnostics.CodeAnalysis;
using Excalibur.Dispatch.Delivery;
public static class ZonedCronExample
{
public static async Task ScheduleAsync<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TMessage>(
IDispatchScheduler scheduler, TMessage message, CancellationToken cancellationToken) where TMessage : class
{
var zone = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
await scheduler.ScheduleRecurringAsync("30 2 * * *", zone,
CronRecurrenceProfile.CronosCompatible, message, cancellationToken);
}
}
The overload without a zone accepts the same explicit profile and uses the configured
CronScheduleOptions.DefaultTimeZone. Existing overloads without a profile remain valid
for installed UTC or provably transition-free zones. Transition zones require an explicit
profile before any row is written. A supplied zone must have the same rules as its installed
identifier; a custom zone cannot silently change when the worker resolves it after restart.
The added scheduler overloads and IScheduleSpec properties are intentional source-breaking
changes for custom implementations; implement the new members explicitly.
CronosCompatible declares one UTC occurrence for gap aliases within a schedule, including
a matching ordinary boundary. Different schedule IDs remain independent. Fixed/noninterval
cron fires at the earlier fold instant; interval cron retains both ordered UTC series.
Cronos defines interval syntax using time-field wildcards, ranges and steps; fixed lists
alone are not interval syntax. Catch-up policy operates on these distinct UTC occurrences
and does not override the known-failure/recovery execution obligation. This declaration
adds no alternative DST algorithms or exactly-once external-effect guarantee.
Rows retain CronRecurrenceProfileId and CronRecurrenceProfileVersion, not a serialized
profile object or timezone. Unknown/partial declarations and unknown zones do not silently
fall back to UTC. Legacy rows remain available for explicit repair; future first admission
requires a valid declaration. Already captured UTC occurrences retain their authority for
retry, recovery, renewal, settlement and release. If current work truly succeeds but future
configuration is invalid, conditional fulfillment may pause the schedule while preserving
its payload, raw configuration and last success; the worker reports
FutureConfigurationBlocked. Repair supplies a valid installed zone/profile and a real
next occurrence with a fresh generation. Failed work still retains/retries/quarantines;
a configuration problem cannot be treated as successful execution. Installed timezone data
controls future instants; the profile does not pin tzdata across machines or upgrades.
Expiring scheduler ownership
A provider with expiring ownership can additionally implement
IScheduleExecutionLeaseRenewal on that same configured store. LeaseDuration is the
positive duration granted at acquisition and each successful renewal, measured by the
provider's authoritative clock. Renewal must atomically check the complete lease tuple
and current expiry. It cannot revive expired, released or replaced ownership, and remains
available during progress settlement until release.
The worker renews while decoding, invoking the handler and settling progress. A rejected, failed or overdue renewal cancels the occurrence and bars new progress requests or catch-up admission. An in-flight progress request may still be accepted by the authoritative store if its ownership remains current and unexpired. Handlers and providers must cooperate with cancellation: cancellation cannot undo an external effect or forcibly terminate user code. Matching release uses an independent bounded token during shutdown. The built-in in-memory store does not expire ownership and needs no renewal.
Each admitted occurrence receives its own asynchronous dependency-injection scope. Its
message context exposes that scope through RequestServices, so handlers can resolve
scoped dependencies. The worker keeps the scope alive through progress settlement and
the matching release attempt, then awaits asynchronous disposal. Catch-up occurrences
receive separate scopes. Dependency disposal must also cooperate with shutdown; a
dependency whose DisposeAsync never completes can delay worker shutdown.
Renewal protects ownership while work runs; it does not establish durable storage, crashed-owner recovery or exactly-once delivery. Test expiry and renewal against the provider's own clock, and test process recovery against its actual backing database.
SQL Server schedule storage
Excalibur.Data.SqlServer includes SqlServerScheduleStore. Apply the package's
scripts/004_CreateScheduleSchema.sql, then
scripts/005_CreateScheduleFailureSchema.sql, then
scripts/006_AddScheduleCronRecurrenceProfile.sql, to the target database before starting the host,
then configure the same store used by time-aware scheduling:
services.AddTimeAwareScheduling();
services.AddSqlServerScheduleStore(options =>
{
options.ConnectionString = schedulesConnectionString;
options.LeaseDuration = TimeSpan.FromMinutes(1);
options.CommandTimeoutSeconds = 30;
options.LockTimeoutMilliseconds = 10_000;
});
The registration supplies the configured IScheduleStore and its durability attestation
together. That same store also implements IScheduleExecutionFailureStore for captured
admission budgets, retained quarantine and expected-token recovery. Cast the selected
store to its execution capabilities; do not resolve a separate authority.
Registration does not create tables or apply these migrations.
The default preserving scheduler profile requires the selected IScheduleStore itself
to implement IScheduleExecutionFailureStore; durability attestation alone is not this
capability. Unsupported stores are refused before hosted scheduling starts. Volatile
opt-in permits restart loss only and does not remove the failure-capability requirement.
Use a writable-primary connection. Command and lock timeouts bound their respective operations; connection-opening settings remain part of the connection string.
AddSqlServerScheduleStore validates options during host startup. The connection string
must be nonblank, the lease duration and command timeout must be positive, and the lock
timeout must be nonnegative. A zero lock timeout fails immediately when the lock is
contended. These configuration checks do not connect to the database or verify that
the schema has been provisioned.
The database persists schedules, administrative generations and the logical store identity. Acquisition, renewal, progress and administration coordinate at the same transaction boundary. Expired ownership becomes eligible for another attempt after a worker dies. Lost commit responses can leave an accepted operation uncertain; the provider does not automatically retry those responses. Handlers must tolerate duplicate external effects.
The failure capability exposes bounded quarantine queries filtered by the exact retained
raw envelope tenant identifier. Null, the literal __untenanted__, empty string, case
and trailing spaces remain distinct; these values are not canonical ambient tenant
partitions. The caller must authorize the query; supplying an identifier is not a credential.
Schedule administration through GetAllAsync, StoreAsync and CompleteAsync is store-global. Optional tenant and correlation values are
message envelope metadata, not a storage partition or an authorization boundary. Null
tenant metadata is preserved and does not become the explicit untenanted identity. The
worker's tenant validation still applies when dispatching.
Ownership uses the database server's UTC clock. Clock adjustments can affect expiry, and
a delayed response can arrive after its grant has elapsed; the worker retains its local
deadline checks. After database restore or cloning, stop workers and rotate the authority
epoch while clearing ownership before resuming. Restoring an old epoch while old workers
remain active is outside the fencing guarantee.
Offline restore, copying or authority-epoch rotation must coordinate current schedules
and retained failure, quarantine and recovery receipts. Do not rotate StoreId
independently and strand that history; ordinary process-restart recovery does not
certify database restore or epoch migration.
Built-In Validators
Excalibur provides IValidateOptions<T> validators for cross-property constraint checking. These go beyond [DataAnnotations] to validate relationships between properties.
Example: LeaderElectionOptionsValidator
public sealed class LeaderElectionOptionsValidator : IValidateOptions<LeaderElectionOptions>
{
public ValidateOptionsResult Validate(string? name, LeaderElectionOptions options)
{
if (options.RenewInterval >= options.LeaseDuration)
{
return ValidateOptionsResult.Fail(
$"RenewInterval ({options.RenewInterval}) must be less than " +
$"LeaseDuration ({options.LeaseDuration}).");
}
if (options.GracePeriod >= options.LeaseDuration)
{
return ValidateOptionsResult.Fail(
$"GracePeriod ({options.GracePeriod}) must be less than " +
$"LeaseDuration ({options.LeaseDuration}).");
}
return ValidateOptionsResult.Success;
}
}
Packages with ValidateOnStart
The following packages register ValidateOnStart() + ValidateDataAnnotations() for their Options classes. Many also include cross-property IValidateOptions<T> validators:
| Package | Options Class | Cross-Property Validator |
|---|---|---|
Excalibur.Dispatch | DispatchTelemetryOptions, CircuitBreakerOptions, TimePolicyOptions, OutboxOptions | Yes |
Excalibur.Dispatch.Observability | ContextObservabilityOptions, TelemetrySanitizerOptions | Yes |
Excalibur.Security | JwtAuthenticationOptions, SigningOptions | Yes |
Excalibur.Dispatch.Resilience.Polly | PollyResilienceOptions | Yes |
Excalibur.Dispatch.Caching | CacheOptions | Yes |
Excalibur.Compliance | ErasureOptions | Yes |
Excalibur.Dispatch.Patterns | ClaimCheckOptions | Yes |
Excalibur.Dispatch.Transport.RabbitMQ | RabbitMqTransportOptions | Yes |
Excalibur.Dispatch.Transport.GooglePubSub | OrderingKeyOptions | Yes |
Excalibur.Dispatch.LeaderElection | LeaderElectionOptions | Yes |
Excalibur.EventSourcing | MaterializedViewOptions, SnapshotUpgradingOptions | Yes |
Excalibur.Saga | SagaOptions | Yes |
Excalibur.Saga.SqlServer | SqlServerSagaStoreOptions, SqlServerSagaTimeoutStoreOptions | Yes |
Excalibur.Cdc | CdcProcessingOptions | Yes |
| Various data providers | SqlServerPersistenceOptions, PostgresPersistenceOptions, CDC state store options | Yes |
Writing Custom Validators
Create an IValidateOptions<T> implementation for cross-property validation in your own Options classes:
public sealed class MyFeatureOptionsValidator : IValidateOptions<MyFeatureOptions>
{
public ValidateOptionsResult Validate(string? name, MyFeatureOptions options)
{
ArgumentNullException.ThrowIfNull(options);
if (options.RetryCount > 0 && options.RetryDelay <= TimeSpan.Zero)
{
return ValidateOptionsResult.Fail(
"RetryDelay must be positive when RetryCount > 0.");
}
return ValidateOptionsResult.Success;
}
}
Register your validator alongside your Options:
services.AddOptions<MyFeatureOptions>()
.ValidateDataAnnotations()
.ValidateOnStart();
services.TryAddEnumerable(
ServiceDescriptor.Singleton<IValidateOptions<MyFeatureOptions>, MyFeatureOptionsValidator>());
Without ValidateOnStart(), misconfigured options are only detected when IOptions<T>.Value is first accessed -- which could be hours into production under a specific code path. ValidateOnStart() fails fast at startup, before any traffic is served.
See Also
- Configuration -- Basic setup and builder API
- Configuration - Environments -- Environment-specific settings and transports
- Dependency Injection -- DI patterns and lifetimes
- Pipeline -- Middleware configuration details