CommunityCodierung & Entwicklunggithub.com

Microsoft.Extensions Konfigurationsmuster

Implementierung von Microsoft.Extensions.Options-Mustern, einschließlich IValidateOptions, stark typisierter Einstellungen, Validierung beim Start und des Options-Musters für sauberes Konfigurationsmanagement.

Was ist Microsoft.Extensions Konfigurationsmuster?

Diese Fähigkeit behandelt die umfassende Nutzung von Microsoft.Extensions.Options in .NET-Anwendungen. Sie zeigt, wie Konfigurationen aus appsettings.json in stark typisierte Klassen gebunden, mit Datenannotations oder dem IValidateOptions-Interface validiert und mit ValidateOnStart beim Start geprüft werden, um Fehler frühzeitig zu erkennen. Die Fähigkeit erklärt die Unterschiede zwischen IOptions<T>, IOptionsSnapshot<T> und IOptionsMonitor<T> und deren Lebensdauer, insbesondere für Hintergrunddienste, die dynamische Konfigurationsänderungen benötigen. Entwickler lernen Anti-Patterns wie das Umgehen der Validierung oder das Vergessen von ValidateOnStart zu vermeiden und erhalten eine klare Anleitung, wie man Konfiguration testbar und wartbar hält. Die Referenzdatei advanced-patterns.md bietet zusätzlich Validatoren mit Abhängigkeiten, benannte Optionen und ein vollständiges Produktionsbeispiel (AkkaSettings) sowie Tests für Validatoren.

Funktioniert mit~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/microsoft-extensions-configuration

Installed? Explore more Codierung & Entwicklung skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Was macht Microsoft.Extensions Konfigurationsmuster?

Wann Sie diese Fähigkeit einsetzen sollten

Verwenden Sie diese Fähigkeit, wenn:

  • Konfiguration aus appsettings.json an streng typisierte Klassen binden
  • Konfiguration beim Anwendungsstart validieren (Fail Fast)
  • Komplexe Validierungslogik für Einstellungen implementieren
  • Konfigurationsklassen entwerfen, die testbar und wartbar sind
  • IOptions, IOptionsSnapshot und IOptionsMonitor verstehen

Referenzdateien

  • advanced-patterns.md: Validatoren mit Abhängigkeiten, benannte Optionen, vollständiges Produktionsbeispiel (AkkaSettings) und Testen von Validatoren

Warum Konfigurationsvalidierung wichtig ist

Das Problem: Anwendungen scheitern oft zur Laufzeit aufgrund von Fehlkonfigurationen – fehlende Verbindungszeichenfolgen, ungültige URLs, Werte außerhalb des zulässigen Bereichs. Diese Fehler treten tief in der Geschäftslogik auf, weit entfernt vom Ort, an dem die Konfiguration geladen wird.

Die Lösung: Konfiguration beim Start validieren. Wenn ungültig, sofort mit einer klaren Fehlermeldung fehlschlagen.

// SCHLECHT: Schlägt zur Laufzeit fehl, wenn jemand versucht, den Dienst zu nutzen
public class EmailService
{
    public EmailService(IOptions<SmtpSettings> options)
    {
        var settings = options.Value;
        // Löst 10 Minuten nach Produktionsstart eine NullReferenceException aus
        _client = new SmtpClient(settings.Host, settings.Port);
    }
}

// GUT: Schlägt beim Start mit klarem Fehler fehl
// "SmtpSettings-Validierung fehlgeschlagen: Host ist erforderlich"

Muster 1: Basis-Optionsbindung

Eine Einstellungsklasse definieren

public class SmtpSettings
{
    public const string SectionName = "Smtp";

    public string Host { get; set; } = string.Empty;
    public int Port { get; set; } = 587;
    public string? Username { get; set; }
    public string? Password { get; set; }
    public bool UseSsl { get; set; } = true;
}

Aus der Konfiguration binden

builder.Services.AddOptions<SmtpSettings>()
    .BindConfiguration(SmtpSettings.SectionName);

// appsettings.json
{
  "Smtp": {
    "Host": "smtp.example.com",
    "Port": 587,
    "Username": "[email protected]",
    "Password": "secret",
    "UseSsl": true
  }
}

In Diensten konsumieren

public class EmailService
{
    private readonly SmtpSettings _settings;

    // IOptions<T> - Singleton, einmal beim Start gelesen
    public EmailService(IOptions<SmtpSettings> options)
    {
        _settings = options.Value;
    }
}

Muster 2: Datenannotations-Validierung

Für einfache Validierungsregeln Datenanmerkungen verwenden:

using System.ComponentModel.DataAnnotations;

public class SmtpSettings
{
    public const string SectionName = "Smtp";

    [Required(ErrorMessage = "SMTP-Host ist erforderlich")]
    public string Host { get; set; } = string.Empty;

    [Range(1, 65535, ErrorMessage = "Port muss zwischen 1 und 65535 liegen")]
    public int Port { get; set; } = 587;

    [EmailAddress(ErrorMessage = "Benutzername muss eine gültige E-Mail-Adresse sein")]
    public string? Username { get; set; }

    public string? Password { get; set; }
    public bool UseSsl { get; set; } = true;
}

Datenannotations-Validierung aktivieren

builder.Services.AddOptions<SmtpSettings>()
    .BindConfiguration(SmtpSettings.SectionName)
    .ValidateDataAnnotations()  // Attributbasierte Validierung aktivieren
    .ValidateOnStart();         // Sofort beim Start validieren

Wichtiger Punkt: .ValidateOnStart() ist entscheidend. Ohne sie wird die Validierung nur ausgeführt, wenn zum ersten Mal auf die Optionen zugegriffen wird.


Muster 3: IValidateOptions für komplexe Validierung

Datenanmerkungen funktionieren für einfache Regeln, aber komplexe Validierung erfordert IValidateOptions<T>:

SzenarioDatenanmerkungenIValidateOptions
Erforderliches FeldJaJa
BereichsprüfungJaJa
Eigenschaftsübergreifende ValidierungNeinJa
Bedingte ValidierungNeinJa
Externe DienstprüfungenNeinJa
Abhängigkeitsinjektion im ValidatorNeinJa

IValidateOptions implementieren

using Microsoft.Extensions.Options;

public class SmtpSettingsValidator : IValidateOptions<SmtpSettings>
{
    public ValidateOptionsResult Validate(string? name, SmtpSettings options)
    {
        var failures = new List<string>();

        if (string.IsNullOrWhiteSpace(options.Host))
            failures.Add("Host ist erforderlich");

        if (options.Port is < 1 or > 65535)
            failures.Add($"Port {options.Port} ist ungültig. Muss zwischen 1 und 65535 liegen");

        // Eigenschaftsübergreifende Validierung
        if (!string.IsNullOrEmpty(options.Username) && string.IsNullOrEmpty(options.Password))
            failures.Add("Passwort ist erforderlich, wenn ein Benutzername angegeben wird");

        // Bedingte Validierung
        if (options.UseSsl && options.Port == 25)
            failures.Add("Port 25 wird normalerweise nicht mit SSL verwendet. Erwägen Sie Port 465 oder 587");

        return failures.Count > 0
            ? ValidateOptionsResult.Fail(failures)
            : ValidateOptionsResult.Success;
    }
}

Den Validator registrieren

builder.Services.AddOptions<SmtpSettings>()
    .BindConfiguration(SmtpSettings.SectionName)
    .ValidateDataAnnotations()
    .ValidateOnStart();

builder.Services.AddSingleton<IValidateOptions<SmtpSettings>, SmtpSettingsValidator>();

Die Reihenfolge ist wichtig: Datenanmerkungen werden zuerst ausgeführt, dann IValidateOptions-Validatoren. Alle Fehlschläge werden zusammen erfasst.

Siehe advanced-patterns.md für Validatoren mit Abhängigkeiten, benannte Optionen und ein vollständiges Produktionsbeispiel.


Muster 4: Optionslebensdauer

SchnittstelleLebensdauerLädt bei Änderung neuAnwendungsfall
IOptions<T>SingletonNeinStatische Konfiguration, einmal gelesen
IOptionsSnapshot<T>ScopedJa (pro Anforderung)Web-Apps, die aktuelle Konfiguration benötigen
IOptionsMonitor<T>SingletonJa (mit Rückruf)Hintergrunddienste, Echtzeit-Updates

IOptionsMonitor für Hintergrunddienste

public class BackgroundWorker : BackgroundService
{
    private readonly IOptionsMonitor<WorkerSettings> _optionsMonitor;
    private WorkerSettings _currentSettings;

    public BackgroundWorker(IOptionsMonitor<WorkerSettings> optionsMonitor)
    {
        _optionsMonitor = optionsMonitor;
        _currentSettings = optionsMonitor.CurrentValue;

        _optionsMonitor.OnChange(settings =>
        {
            _currentSettings = settings;
        });
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await DoWorkAsync();
            await Task.Delay(_currentSettings.PollingInterval, stoppingToken);
        }
    }
}

Muster 5: Nachkonfiguration

Optionen nach der Bindung, aber vor der Validierung ändern:

builder.Services.AddOptions<ApiSettings>()
    .BindConfiguration("Api")
    .PostConfigure(options =>
    {
        if (!string.IsNullOrEmpty(options.BaseUrl) && !options.BaseUrl.EndsWith('/'))
            options.BaseUrl += '/';

        options.Timeout ??= TimeSpan.FromSeconds(30);
    })
    .ValidateDataAnnotations()
    .ValidateOnStart();

Anti-Patterns, die Sie vermeiden sollten

1. Manueller Konfigurationszugriff

// SCHLECHT: Umgeht Validierung, schwer zu testen
public class MyService
{
    public MyService(IConfiguration configuration)
    {
        var host = configuration["Smtp:Host"]; // Keine Validierung!
    }
}

// GUT: Streng typisiert, validiert
public class MyService
{
    public MyService(IOptions<SmtpSettings> options)
    {
        var host = options.Value.Host; // Beim Start validiert
    }
}

2. Validierung im Konstruktor

// SCHLECHT: Validierung erfolgt zur Laufzeit, nicht beim Start
public class MyService
{
    public MyService(IOptions<Settings> options)
    {
        if (string.IsNullOrEmpty(options.Value.Required))
            throw new ArgumentException("Erforderlich fehlt"); // Zu spät!
    }
}

// GUT: Validierung beim Start über IValidateOptions + ValidateOnStart()

3. ValidateOnStart vergessen

// SCHLECHT: Validierung wird nur ausgeführt, wenn zum ersten Mal darauf zugegriffen wird
builder.Services.AddOptions<Settings>()
    .ValidateDataAnnotations(); // ValidateOnStart fehlt!

// GUT: Schlägt sofort fehl, wenn ungültig
builder.Services.AddOptions<Settings>()
    .ValidateDataAnnotations()
    .ValidateOnStart();

4. Ausnahme in IValidateOptions werfen

// SCHLECHT: Wirft Ausnahme, unterbricht Validierungskette
public ValidateOptionsResult Validate(string? name, Settings options)
{
    if (options.Value < 0)
        throw new ArgumentException("Wert darf nicht negativ sein"); // Falsch!
    return ValidateOptionsResult.Success;
}

// GUT: Fehlerergebnis zurückgeben
public ValidateOptionsResult Validate(string? name, Settings options)
{
    if (options.Value < 0)
        return ValidateOptionsResult.Fail("Wert darf nicht negativ sein");
    return ValidateOptionsResult.Success;
}

Zusammenfassung

PrinzipImplementierung
Fail Fast.ValidateOnStart()
Streng typisiertAn POCO-Klassen binden
Einfache ValidierungDatenanmerkungen
Komplexe ValidierungIValidateOptions<T>
Eigenschaftsübergreifende RegelnIValidateOptions<T>
UmgebungsbewusstIHostEnvironment injizieren
TestbarValidatoren sind einfache Klassen

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

Verwandte Skills