C#

Lesson 09

Options configuration

Bind configuration into validated options objects instead of reading string keys across business code.

Good Code

src/ReviewOptions.cs
public sealed class ReviewOptions
{
    public const string SectionName = "Reviews";
    public required Uri ApiBaseUrl { get; init; }
    public int PageSize { get; init; } = 50;
}

builder.Services
    .AddOptions<ReviewOptions>()
    .BindConfiguration(ReviewOptions.SectionName)
    .Validate(options => options.PageSize is >= 1 and <= 100)
    .ValidateOnStart();

// Validated options keep string keys out of service code.

Bad Code

ReviewService.cs
public sealed class ReviewService
{
    public ReviewService(IConfiguration configuration)
    {
        // String keys in services delay config errors until runtime calls.
        apiBaseUrl = new Uri(configuration["Reviews:ApiUrl"]!);
        pageSize = int.Parse(configuration["Reviews:PageSize"]!);
    }
}

Review Notes

What to review

Good Code

The good version binds a named section to ReviewOptions and validates it at startup. Services can receive typed values instead of raw configuration.

Bad Code

The bad version reads string keys inside a service constructor. Missing or malformed config fails only when that service is built, and typos are hard to spot.

Takeaways

  • Configuration should cross into services as typed values that were validated during startup.