A configuration object can exist and still be unusable. A worker with a missing queue name or a batch size of zero should be rejected before its work begins. This tutorial builds and tests that ordering rule for a small C# console application.
The example uses an explicit DataAnnotations guard and a callback that represents the point where work would start. It tests that guard in process. It does not start a hosted service or test a dependency injection container.
Choose the startup boundary
Our contract is small: the queue name must be present, and batch size must be between 1 and 100. Invalid options return validation errors and never invoke the work callback. Valid options invoke it exactly once with the same options instance.
For applications using the .NET options infrastructure, Microsoft documents ValidateOnStart to arrange validation at host startup. Use that integration for a hosted application and test its actual host startup separately. The manual guard below is for a console application whose startup sequence you control. See the official options validation guidance.
Run the complete startup guard test
Create a .NET 10 console project with the commands below, then replace its entire Program.cs with the complete program that follows. No additional packages are needed. The example was built for net10.0 with nullable analysis and warnings treated as errors, and its output was asserted in an offline container on November 8, 2026.
dotnet new console --framework net10.0 --name StartupOptions
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
public static class Program
{
public static void Main()
{
Check("missing name", new WorkerOptions { BatchSize = 10 }, false,
"QueueName is required.");
Check("blank name", new WorkerOptions { QueueName = " ", BatchSize = 10 }, false,
"QueueName is required.");
Check("missing batch", new WorkerOptions { QueueName = "jobs" }, false,
"BatchSize must be between 1 and 100.");
Check("batch too large", new WorkerOptions { QueueName = "jobs", BatchSize = 101 }, false,
"BatchSize must be between 1 and 100.");
Check("lower boundary", new WorkerOptions { QueueName = "jobs", BatchSize = 1 }, true);
Check("upper boundary", new WorkerOptions { QueueName = "jobs", BatchSize = 100 }, true);
var rangeOnlyFailure = new WorkerOptions { QueueName = "jobs", BatchSize = 0 };
var ignoredRangeErrors = new List<ValidationResult>();
bool incompleteCheck = Validator.TryValidateObject(rangeOnlyFailure,
new ValidationContext(rangeOnlyFailure), ignoredRangeErrors,
validateAllProperties: false);
Require(incompleteCheck && ignoredRangeErrors.Count == 0,
"The negative control no longer demonstrates skipped range validation.");
Console.WriteLine("negative control: required-only check missed invalid batch");
Console.WriteLine("All startup guard assertions passed.");
}
public static bool TryStart(WorkerOptions options, Action<WorkerOptions> startWork,
out string[] errors)
{
var results = new List<ValidationResult>();
bool valid = Validator.TryValidateObject(options,
new ValidationContext(options), results, validateAllProperties: true);
errors = results.Select(result => result.ErrorMessage ?? "Invalid options.").ToArray();
if (!valid)
return false;
startWork(options);
return true;
}
private static void Check(string label, WorkerOptions options, bool expectedStart,
params string[] expectedErrors)
{
int starts = 0;
bool started = TryStart(options, received =>
{
Require(ReferenceEquals(received, options), "Options instance changed.");
starts++;
}, out string[] errors);
Require(started == expectedStart, label + ": unexpected return value.");
Require(starts == (expectedStart ? 1 : 0), label + ": unexpected work invocation.");
Require(errors.OrderBy(error => error, StringComparer.Ordinal).SequenceEqual(
expectedErrors.OrderBy(error => error, StringComparer.Ordinal)),
label + ": unexpected validation errors.");
Console.WriteLine(label + (started ? ": started once" : ": blocked before work"));
}
private static void Require(bool condition, string message)
{
if (!condition)
throw new InvalidOperationException(message);
}
}
public sealed class WorkerOptions
{
[Required(ErrorMessage = "QueueName is required.")]
public string? QueueName { get; set; }
[Range(1, 100, ErrorMessage = "BatchSize must be between 1 and 100.")]
public int BatchSize { get; set; }
}
Run the project after replacing the generated program:
dotnet run --project StartupOptions -p:TreatWarningsAsErrors=true
Expected output:
missing name: blocked before work
blank name: blocked before work
missing batch: blocked before work
batch too large: blocked before work
lower boundary: started once
upper boundary: started once
negative control: required-only check missed invalid batch
All startup guard assertions passed.
Assert the effect, not just the validation result
TryStart gathers validation results before it reaches startWork. Microsoft documents that TryValidateObject returns a Boolean and can populate a collection of failed validations. Passing validateAllProperties: true enables validation of property attributes beyond required checks. See the Validator API reference for .NET 10.
Each Check call asserts three separate outcomes: the return value, the number of callback invocations, and the exact error messages. If validation still returns false after a future refactor but the callback has already run, the invocation count fails the test. Checking only the Boolean would miss that ordering bug.
The four rejected cases cover a null name, a whitespace name, the integer default of zero, and a value above the upper bound. Both accepted boundary values must start once and produce no errors. Explicit attribute messages keep these assertions independent of the framework’s default message wording; sorting avoids relying on the order of failures.
The final negative control intentionally runs the zero batch size through required-only validation. It passes that incomplete check because its queue name is present. The earlier missing-batch case uses the real guard and rejects the same invalid batch size. Together, the cases make it harder to accidentally replace the complete validation call with a required-only check.
What this test does not establish
The callback is a probe, not a running worker. These assertions establish the guard’s ordering and selected validation behavior. They do not establish that a queue exists, credentials work, configuration binding supplies the intended values, or a hosted service refuses to start. A production caller must load its options, handle a false result, and avoid entering its work loop. This executable is a test harness, so expected rejection cases still end with a successful test-process exit.
Keep the options object and callback non-null when calling this helper. Treat the validated instance as fixed during startup: its setters remain public, and this guard provides no protection against another thread changing it later. This example also does not define how callback exceptions should be handled.
Nested settings need their own validation plan: TryValidateObject does not recursively validate child objects. Its API also carries trimming-related warnings; this ordinary console build does not verify trimmed or Native AOT deployment. See the same API remarks and annotations before expanding the model or changing deployment mode.
For a different validation design, compare our tested pattern matching validation example. For the distinction between initialization requirements and valid runtime values, continue with required members and construction guarantees.