Communitygithub.com

dotnet-patterns

Idiomatische C#- und .NET-Patterns, Konventionen, Dependency Injection, async/await und Best Practices für robuste, wartbare .NET-Anwendungen. Verwenden beim Schreiben oder Überprüfen von C#/.NET-Code – DI, async oder allgemeine Konventionen.

Was ist dotnet-patterns?

Diese Skill-Anleitung definiert idiomatische C#- und .NET-Entwicklungsmuster, die speziell für Entwickler und KI-Agenten wie Claude Code, Cursor oder Codex konzipiert sind. Sie aktiviert sich beim Schreiben, Überprüfen oder Refactorn von C#-Code sowie beim Entwerfen von ASP.NET Core-Diensten. Die Anleitung deckt Kernprinzipien wie Unveränderlichkeit (Records, init-only Properties), explizite Nullable- und Zugriffsmodifikatoren sowie Abhängigkeit von Abstraktionen (Interfaces, DI-Registrierung) ab. Zudem werden wichtige Async/Await-Patterns (durchgängig async, CancellationToken, parallele Operationen mit Task.WhenAll), das Options Pattern für stark typisierte Konfiguration, das Result Pattern für explizite Erfolgs-/Fehlerrückgaben, das Repository Pattern mit EF Core, Middleware-Pipelines, Minimal-API-Routengruppen und Guard-Klauseln behandelt. Die Anleitung enthält konkrete Codebeispiele, die zeigen, wie typische Anti-Patterns wie async void, .Result/.Wait, leere catch-Blöcke, manuelle Instanziierung von Diensten oder mutable statische Zustände vermieden werden. Plattformunabhängig einsetzbar für jeden .NET-Entwicklungs-Stack.

Funktioniert mit~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/dotnet-patterns

In Ihrer bevorzugten KI fragen

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

Dokumentation

.NET-Entwicklungsmuster

Idiomatische C#- und .NET-Muster zum Erstellen robuster, performanter und wartbarer Anwendungen.

Wann aktivieren

  • Schreiben von neuem C#-Code
  • Überprüfen von C#-Code
  • Refactorn vorhandener .NET-Anwendungen
  • Entwerfen von Dienstarten mit ASP.NET Core

Kernprinzipien

1. Unveränderlichkeit bevorzugen

Verwenden Sie Records und init-only-Properties für Datenmodelle. Veränderlichkeit sollte eine explizite, begründete Wahl sein.

// Gut: Unveränderliches Wertobjekt
public sealed record Money(decimal Betrag, string Währung);

// Gut: Unveränderliches DTO mit Init-Setzern
public sealed class CreateOrderRequest
{
    public required string KundenId { get; init; }
    public required IReadOnlyList<OrderItem> Positionen { get; init; }
}

// Schlecht: Veränderliches Modell mit öffentlichen Setzern
public class Bestellung
{
    public string KundenId { get; set; }
    public List<OrderItem> Positionen { get; set; }
}

2. Explizit statt implizit

Seien Sie klar bei Nullable, Zugriffsmodifikatoren und Absicht.

// Gut: Explizite Zugriffsmodifikatoren und Nullable
public sealed class BenutzerService
{
    private readonly IBenutzerRepository _repository;
    private readonly ILogger<BenutzerService> _logger;

    public BenutzerService(IBenutzerRepository repository, ILogger<BenutzerService> logger)
    {
        _repository = repository ?? throw new ArgumentNullException(nameof(repository));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<Benutzer?> FindePerIdAsync(Guid id, CancellationToken cancellationToken)
    {
        return await _repository.FindByIdAsync(id, cancellationToken);
    }
}

3. Von Abstraktionen abhängen

Verwenden Sie Schnittstellen für Dienstgrenzen. Registrierung über DI-Container.

// Gut: Schnittstellenbasierte Abhängigkeit
public interface IBestellungRepository
{
    Task<Bestellung?> FindePerIdAsync(Guid id, CancellationToken cancellationToken);
    Task<IReadOnlyList<Bestellung>> FindePerKundeAsync(string kundenId, CancellationToken cancellationToken);
    Task FügeHinzuAsync(Bestellung bestellung, CancellationToken cancellationToken);
}

// Registrierung
builder.Services.AddScoped<IBestellungRepository, SqlBestellungRepository>();

Async/Await-Muster

Korrekte Async-Verwendung

// Gut: Async durchgängig mit CancellationToken
public async Task<BestellungsZusammenfassung> HoleBestellungsZusammenfassungAsync(
    Guid bestellungsId,
    CancellationToken cancellationToken)
{
    var bestellung = await _repository.FindByIdAsync(bestellungsId, cancellationToken)
        ?? throw new NotFoundException($"Bestellung {bestellungsId} nicht gefunden");

    var kunde = await _kundenService.HoleAsync(bestellung.KundenId, cancellationToken);

    return new BestellungsZusammenfassung(bestellung, kunde);
}

// Schlecht: Blockieren auf async
public BestellungsZusammenfassung HoleBestellungsZusammenfassung(Guid bestellungsId)
{
    var bestellung = _repository.FindByIdAsync(bestellungsId, CancellationToken.None).Result; // Deadlock-Risiko
    return new BestellungsZusammenfassung(bestellung);
}

Parallele Async-Operationen

// Gut: Gleichzeitige unabhängige Operationen
public async Task<DashboardDaten> LadeDashboardAsync(CancellationToken cancellationToken)
{
    var bestellungenTask = _bestellungsService.HoleAktuelleAsync(cancellationToken);
    var metrikenTask = _metrikService.HoleAktuelleAsync(cancellationToken);
    var benachrichtigungenTask = _benachrichtigungsService.HoleAktiveAsync(cancellationToken);

    await Task.WhenAll(bestellungenTask, metrikenTask, benachrichtigungenTask);

    return new DashboardDaten(
        Bestellungen: await bestellungenTask,
        Metriken: await metrikenTask,
        Benachrichtigungen: await benachrichtigungenTask);
}

Options-Muster

Binden Sie Konfigurationsabschnitte an stark typisierte Objekte.

public sealed class SmtpOptionen
{
    public const string AbschnittsName = "Smtp";

    public required string Host { get; init; }
    public required int Port { get; init; }
    public required string Benutzername { get; init; }
    public bool BenutzeSsl { get; init; } = true;
}

// Registrierung
builder.Services.Configure<SmtpOptionen>(
    builder.Configuration.GetSection(SmtpOptionen.AbschnittsName));

// Verwendung via Injection
public class EmailDienst(IOptions<SmtpOptionen> optionen)
{
    private readonly SmtpOptionen _smtp = optionen.Value;
}

Ergebnis-Muster

Geben Sie expliziten Erfolg/Misserfolg zurück, anstatt bei erwarteten Fehlern Ausnahmen zu werfen.

public sealed record Ergebnis<T>
{
    public bool IstErfolg { get; }
    public T? Wert { get; }
    public string? Fehler { get; }

    private Ergebnis(T wert) { IstErfolg = true; Wert = wert; }
    private Ergebnis(string fehler) { IstErfolg = false; Fehler = fehler; }

    public static Ergebnis<T> Erfolg(T wert) => new(wert);
    public static Ergebnis<T> Fehlschlag(string fehler) => new(fehler);
}

// Verwendung
public async Task<Ergebnis<Bestellung>> PlatziereBestellungAsync(CreateOrderRequest anfrage)
{
    if (anfrage.Positionen.Count == 0)
        return Ergebnis<Bestellung>.Fehlschlag("Bestellung muss mindestens eine Position enthalten");

    var bestellung = Bestellung.Erstellen(anfrage);
    await _repository.FügeHinzuAsync(bestellung, CancellationToken.None);
    return Ergebnis<Bestellung>.Erfolg(bestellung);
}

Repository-Muster mit EF Core

public sealed class SqlBestellungRepository : IBestellungRepository
{
    private readonly AppDbContext _db;

    public SqlBestellungRepository(AppDbContext db) => _db = db;

    public async Task<Bestellung?> FindePerIdAsync(Guid id, CancellationToken cancellationToken)
    {
        return await _db.Bestellungen
            .Include(b => b.Positionen)
            .AsNoTracking()
            .FirstOrDefaultAsync(b => b.Id == id, cancellationToken);
    }

    public async Task<IReadOnlyList<Bestellung>> FindePerKundeAsync(
        string kundenId,
        CancellationToken cancellationToken)
    {
        return await _db.Bestellungen
            .Where(b => b.KundenId == kundenId)
            .OrderByDescending(b => b.ErstelltAm)
            .AsNoTracking()
            .ToListAsync(cancellationToken);
    }

    public async Task FügeHinzuAsync(Bestellung bestellung, CancellationToken cancellationToken)
    {
        _db.Bestellungen.Add(bestellung);
        await _db.SaveChangesAsync(cancellationToken);
    }
}

Middleware und Pipeline

// Benutzerdefinierte Middleware
public sealed class RequestTimingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<RequestTimingMiddleware> _logger;

    public RequestTimingMiddleware(RequestDelegate next, ILogger<RequestTimingMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext kontext)
    {
        var stopwatch = Stopwatch.StartNew();
        try
        {
            await _next(kontext);
        }
        finally
        {
            stopwatch.Stop();
            _logger.LogInformation(
                "Anfrage {Methode} {Pfad} abgeschlossen in {VerstricheneMs}ms mit Status {Statuscode}",
                kontext.Request.Method,
                kontext.Request.Path,
                stopwatch.ElapsedMilliseconds,
                kontext.Response.StatusCode);
        }
    }
}

Minimal-API-Muster

// Organisiert mit Routengruppen
var bestellungen = app.MapGroup("/api/bestellungen")
    .RequireAuthorization()
    .WithTags("Bestellungen");

bestellungen.MapGet("/{id:guid}", async (
    Guid id,
    IBestellungRepository repository,
    CancellationToken cancellationToken) =>
{
    var bestellung = await repository.FindePerIdAsync(id, cancellationToken);
    return bestellung is not null
        ? TypedResults.Ok(bestellung)
        : TypedResults.NotFound();
});

bestellungen.MapPost("/", async (
    CreateOrderRequest anfrage,
    IBestellungsService service,
    CancellationToken cancellationToken) =>
{
    var ergebnis = await service.PlatziereBestellungAsync(anfrage, cancellationToken);
    return ergebnis.IstErfolg
        ? TypedResults.Created($"/api/bestellungen/{ergebnis.Wert!.Id}", ergebnis.Wert)
        : TypedResults.BadRequest(ergebnis.Fehler);
});

Guard-Klauseln

// Gut: Frühe Rückgaben mit klarer Validierung
public async Task<VerarbeitungsErgebnis> VerarbeiteZahlungAsync(
    ZahlungsAnfrage anfrage,
    CancellationToken cancellationToken)
{
    ArgumentNullException.ThrowIfNull(anfrage);

    if (anfrage.Betrag <= 0)
        throw new ArgumentOutOfRangeException(nameof(anfrage.Betrag), "Betrag muss positiv sein");

    if (string.IsNullOrWhiteSpace(anfrage.Währung))
        throw new ArgumentException("Währung ist erforderlich", nameof(anfrage.Währung));

    // Der Happy Path wird hier ohne Verschachtelung fortgesetzt
    var gateway = _gatewayFactory.Erstellen(anfrage.Währung);
    return await gateway.BelastungDurchführenAsync(anfrage, cancellationToken);
}

Anti-Patterns, die vermieden werden sollten

Anti-PatternLösung
async void-MethodenTask zurückgeben (außer Ereignisbehandlern)
.Result oder .Wait()await verwenden
catch (Exception) { }Behandeln oder mit Kontext erneut werfen
new Service() in KonstruktorenKonstruktor-Injection verwenden
public-FelderProperties mit entsprechenden Zugriffsmodifikatoren verwenden
dynamic in GeschäftslogikGenerics oder explizite Typen verwenden
Veränderlicher static-ZustandDI-Scoping oder ConcurrentDictionary verwenden
string.Format in SchleifenStringBuilder oder interpolierte String-Handler verwenden

Individual skills in this repo

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

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

Verwandte Skills