How to validate a C# nested Options class?
07:29 04 Sep 2023

Using the C# Options pattern and THIS question/answer as example.

I've decided to move the options from their original place at the AnkiOptions class to a nested LocalPath class. I've done this in order to separate different configs into their own logical groups while also being able to receive a single Option instance from the DI. I do have a feel that this increases the coupling between the option sections. So if that goes against the Options pattern remarks are welcome.

With having the following appsettings.json:

{
  "Anki": {
    "LocalPath": {
      "LastDuplicateTimestampCheckFile": "./anki-db-files/last-duplicate-check",
      "MainDbCollectionFile": "./anki-db-files/collection.anki2",
      "WalFile": "./anki-db-files/collection.anki2-wal"
    }
  }
}

Having an AnkiOptions class:

public sealed class AnkiOptions
{
    public const string AnkiOptionsConfigSection = "Anki";

    public LocalPath LocalPath { get; set; }
}

And a LocalPath class:

using System.ComponentModel.DataAnnotations;

public class LocalPath
{
    [Required(AllowEmptyStrings = false)]
    public string LastDuplicateTimestampCheckFile { get; set; }

    [Required(AllowEmptyStrings = false)]
    public string MainDbCollectionFile { get; set; }

    [Required(AllowEmptyStrings = false)]
    public string WalFile { get; set; }
}

When the options were inside the AnkiOptions class the way i validated them was the following:

services
       .AddOptions()
       .Bind(context.Configuration.GetSection(AnkiOptions.AnkiOptionsConfigSection))
       .ValidateDataAnnotations();

How do i validate the options in LocalPath? Shall i register LocalPath as an option and request it from DI in the constructor of the AnkiOptions class? Not sure if that'll work. Or is there some other way to validate nested options?

c#