Logo vun Dotnet Patterns

Dotnet Patterns

Communautéit
j4flmao
dotnet-patterns

Use this skill when the user says 'dotnet MediatR pattern', 'dotnet pipeline behavior', 'dotnet Result pattern', 'EF Core performance', 'EF Core outbox', 'dotnet FluentValidation', 'dotnet event sourcing'. Implements .NET application patterns: mediator pipeline behaviors, Result types, EF Core query optimization, outbox, simple event store and caching decorators. Do NOT use for: solution/project structure (dotnet-architecture), non-.NET stacks.

Iwwersiicht

Editeurj4flmao
Repositoryagent-skills
Skill-Nummdotnet-patterns
Stären
41
Forks
6
Matgeliwwert Fichieren
6
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • 6 matgeliwwert Dateien

    Skripten, Virlagen a Referenzen, déi de Modell beim Schaffe liese kann. D'Dateie kënnen nëmme gelies ginn a ginn ni ausgeféiert.

  • Open Source

    Vum j4flmao op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Dotnet Patterns an TypingMind, fir e mat all LLM ze benotzen, oder füügt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vun GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier hei drënner an a bestätegt.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/dotnet/patterns
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill afügen → Vu GitHub-URL, pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an de Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/backend/dotnet/patterns .claude/skills/dotnet-patterns
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Dotnet Patterns an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Dotnet Patterns automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Dotnet Patterns net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Keys.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

.NET Patterns

Purpose

Implement production-grade .NET patterns — MediatR pipeline behaviors, CQRS with separate models, Result pattern for explicit error handling, EF Core performance patterns, and event sourcing.

Agent Protocol

Trigger

User request includes: dotnet MediatR pattern, dotnet CQRS, dotnet Result pattern, dotnet EF Core, dotnet pipeline behavior, dotnet FluentValidation, dotnet AutoMapper.

Input Context

  • Architecture (Clean Architecture, Vertical Slices)
  • ORM (EF Core, Dapper)
  • Patterns needed (CQRS, Event Sourcing, Outbox, Saga)
  • Testing approach (xUnit, NUnit)

Output Artifact

Code examples for requested patterns — pipeline behavior, CQRS handler, Result type, EF optimization.

Response Format

Code-first output. Pattern name, problem statement, implementation. No preamble, no postamble.

Completion Criteria

  • MediatR pipeline behaviors ordered
  • CQRS with separate Command/Query handlers
  • Result type with implicit conversions
  • EF Core query optimization applied
  • Unit of Work pattern with SaveChangesAsync

Max Response Length

4096 tokens

Architecture Decision Trees

Pipeline Behavior Order

OrderBehaviorPurpose
1LoggingBehaviorLog request start/end with timing
2ValidationBehaviorValidate before processing
3PerformanceBehaviorWarn if > threshold (500ms)
4UnhandledExceptionBehaviorCatch and wrap unhandled
5TransactionBehaviorWrap in DB transaction

Pipeline behaviors run in registration order (first added = outer wrapper, runs first).

FluentValidation vs Data Annotations

CriterionFluentValidationData Annotations
SeparationExternal to modelOn model properties
Conditional rulesYes (When/Unless)Limited
Cross-propertyYes (Must)No
DI supportYes (inject services)No
TestabilityEasy (validator per model)Requires model instantiation

Decision: Complex validation rules → FluentValidation. Simple non-null/range checks → Data Annotations.

Workflow

Step 1: MediatR Pipeline Behaviors

csharp
// Application/Common/Behaviors/PerformanceBehavior.cs
public class PerformanceBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
{
    private readonly ILogger<PerformanceBehavior<TRequest, TResponse>> _logger;

    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken ct)
    {
        const int threshold = 500;
        var sw = Stopwatch.StartNew();
        var response = await next();
        sw.Stop();

        if (sw.ElapsedMilliseconds > threshold)
        {
            _logger.LogWarning("Long running request: {Name} ({Elapsed}ms)",
                typeof(TRequest).Name, sw.ElapsedMilliseconds);
        }

        return response;
    }
}

// Application/Common/Behaviors/TransactionBehavior.cs
public class TransactionBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
{
    private readonly AppDbContext _context;

    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken ct)
    {
        if (request is IQuery<TResponse>) return await next();

        await using var transaction = await _context.Database.BeginTransactionAsync(ct);
        try
        {
            var response = await next();
            await transaction.CommitAsync(ct);
            return response;
        }
        catch
        {
            await transaction.RollbackAsync(ct);
            throw;
        }
    }
}

Step 2: Result Pattern

csharp
// Application/Common/Models/Result.cs
public class Result<T>
{
    private readonly T? _value;
    public T Value => IsSuccess ? _value! : throw new InvalidOperationException("No value on failure");
    public bool IsSuccess { get; }
    public bool IsFailure => !IsSuccess;
    public Error Error { get; }

    private Result(T value)
    {
        _value = value;
        IsSuccess = true;
        Error = Error.None();
    }

    private Result(Error error)
    {
        IsSuccess = false;
        Error = error;
    }

    public static Result<T> Success(T value) => new(value);
    public static Result<T> Failure(Error error) => new(error);

    public TOut Match<TOut>(Func<T, TOut> onSuccess, Func<Error, TOut> onFailure)
        => IsSuccess ? onSuccess(_value!) : onFailure(Error);
}

// Application/Common/Models/Error.cs
public record Error(string Code, string Message)
{
    public static Error None() => new(string.Empty, string.Empty);
    public static Error NotFound(string entity) => new("NOT_FOUND", $"{entity} not found");
    public static Error Validation(string message) => new("VALIDATION_ERROR", message);
    public static Error Conflict(string message) => new("CONFLICT", message);
}

// Usage in handler
public async Task<Result<OrderDto>> Handle(CreateOrderCommand request, CancellationToken ct)
{
    var existing = await _repository.FindByOrderNumber(request.OrderNumber);
    if (existing is not null)
        return Result<OrderDto>.Failure(Error.Conflict("Order number already exists"));

    var order = new Order(request.OrderNumber);
    await _repository.AddAsync(order);
    return Result<OrderDto>.Success(_mapper.Map<OrderDto>(order));
}

// Controller consumes result
[HttpPost]
public async Task<IActionResult> CreateOrder(CreateOrderCommand command)
{
    var result = await _mediator.Send(command);
    return result.Match<IActionResult>(
        onSuccess: dto => CreatedAtAction(nameof(GetById), new { id = dto.Id }, dto),
        onFailure: error => error.Code switch
        {
            "NOT_FOUND" => NotFound(new { error.Message }),
            "VALIDATION_ERROR" => BadRequest(new { error.Message }),
            "CONFLICT" => Conflict(new { error.Message }),
            _ => StatusCode(500, new { error.Message }),
        }
    );
}

Step 3: EF Core Query Optimization

csharp
// Repository with optimized queries
public class OrderRepository : IOrderRepository
{
    private readonly AppDbContext _context;

    public async Task<Order?> GetByIdWithItemsAsync(Guid id)
    {
        return await _context.Orders
            .Include(o => o.Items)
            .AsSplitQuery()  // Avoid cartesian explosion
            .FirstOrDefaultAsync(o => o.Id == id);
    }

    public async Task<PagedResult<OrderSummary>> GetPagedAsync(int page, int size)
    {
        var query = _context.Orders
            .AsNoTracking()
            .OrderByDescending(o => o.CreatedAt).ThenBy(o => o.Id) // stable order required for paging
            .Select(o => new OrderSummary
            {
                Id = o.Id,
                OrderNumber = o.OrderNumber,
                Status = o.Status,
                ItemCount = o.Items.Count,
                Total = o.Items.Sum(i => i.Price * i.Quantity)
            });

        var total = await query.CountAsync();
        var items = await query
            .Skip((page - 1) * size)
            .Take(size)
            .ToListAsync();

        return new PagedResult<OrderSummary>(items, total, page, size);
    }

    public async Task BulkUpdateStatusAsync(OrderStatus fromStatus, OrderStatus toStatus)
    {
        await _context.Orders
            .Where(o => o.Status == fromStatus)
            .ExecuteUpdateAsync(s => s.SetProperty(o => o.Status, toStatus));
    }
}

// Compiled query for hot paths
private static readonly Func<AppDbContext, Guid, Task<Order?>> GetOrderById =
    EF.CompileAsyncQuery((AppDbContext ctx, Guid id) =>
        ctx.Orders.AsNoTracking().FirstOrDefault(o => o.Id == id));

Step 4: Outbox Pattern for Reliable Messaging

csharp
// Domain/DomainEvents/IDomainEvent.cs
public interface IDomainEvent
{
    Guid EventId { get; }
    DateTime OccurredOn { get; }
}

public abstract record DomainEvent : IDomainEvent
{
    public Guid EventId { get; init; } = Guid.NewGuid();
    public DateTime OccurredOn { get; init; } = DateTime.UtcNow;
}

// Infrastructure/Persistence/OutboxMessage.cs
public class OutboxMessage
{
    public Guid Id { get; set; }
    public string Type { get; set; } = string.Empty;
    public string Content { get; set; } = string.Empty;
    public DateTime OccurredOn { get; set; }
    public DateTime? ProcessedOn { get; set; }
    public string? Error { get; set; }
}

// Save domain events as outbox messages
public override async Task<int> SaveChangesAsync(CancellationToken ct = default)
{
    var domainEvents = ChangeTracker.Entries<IAggregateRoot>()
        .Select(e => e.Entity)
        .SelectMany(e =>
        {
            var events = e.DomainEvents.ToList();
            e.ClearDomainEvents();
            return events;
        })
        .ToList();

    var outboxMessages = domainEvents.Select(e => new OutboxMessage
    {
        Id = Guid.NewGuid(),
        Type = e.GetType().AssemblyQualifiedName!,
        Content = JsonSerializer.Serialize(e, _jsonOptions),
        OccurredOn = DateTime.UtcNow,
    }).ToList();

    OutboxMessages.AddRange(outboxMessages);

    return await base.SaveChangesAsync(ct);
}

Step 5: Event Sourcing with EF Core

csharp
// Domain/Events/OrderEvents.cs
public record OrderCreatedEvent(Guid OrderId, string OrderNumber) : DomainEvent;
public record OrderItemAddedEvent(Guid OrderId, string Product, decimal Price, int Quantity) : DomainEvent;
public record OrderConfirmedEvent(Guid OrderId) : DomainEvent;

// Infrastructure/Persistence/EventStore.cs
public class EventStore : IEventStore
{
    private readonly AppDbContext _context;

    // Requires a UNIQUE index on (AggregateId, Version): a concurrent writer that read the
    // same expectedVersion fails with DbUpdateException instead of silently interleaving.
    public async Task AppendEventsAsync(Guid aggregateId, IEnumerable<IDomainEvent> events, int expectedVersion)
    {
        var version = expectedVersion;
        var eventData = events.Select(e => new EventDescriptor
        {
            AggregateId = aggregateId,
            EventType = e.GetType().Name,
            EventData = JsonSerializer.Serialize(e, e.GetType()),
            Version = ++version,
            Timestamp = e.OccurredOn,
        }).ToList();

        _context.EventDescriptors.AddRange(eventData);
        await _context.SaveChangesAsync();
    }

    public async Task<List<IDomainEvent>> GetEventsAsync(Guid aggregateId)
    {
        var descriptors = await _context.EventDescriptors
            .Where(d => d.AggregateId == aggregateId)
            .OrderBy(d => d.Version)
            .ToListAsync();

        return descriptors.Select(d =>
            JsonSerializer.Deserialize(d.EventData, GetEventType(d.EventType)) as IDomainEvent)
            .ToList()!;
    }

    private Type GetEventType(string eventType) => eventType switch
    {
        nameof(OrderCreatedEvent) => typeof(OrderCreatedEvent),
        nameof(OrderItemAddedEvent) => typeof(OrderItemAddedEvent),
        nameof(OrderConfirmedEvent) => typeof(OrderConfirmedEvent),
        _ => throw new InvalidOperationException($"Unknown event: {eventType}")
    };
}

Production Considerations

EF Core Connection Resiliency

csharp
services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(
        connectionString,
        sqlOptions =>
        {
            sqlOptions.EnableRetryOnFailure(
                maxRetryCount: 3,
                maxRetryDelay: TimeSpan.FromSeconds(10),
                errorNumbersToAdd: null);
            sqlOptions.CommandTimeout(30);
        }));

Caching with LazyCache or IDistributedCache

csharp
public class CachedOrderRepository : IOrderRepository
{
    private readonly IOrderRepository _inner;
    private readonly IDistributedCache _cache;

    public async Task<Order?> GetByIdAsync(Guid id)
    {
        var cacheKey = $"order:{id}";
        var cached = await _cache.GetStringAsync(cacheKey);
        if (cached is not null) return JsonSerializer.Deserialize<Order>(cached);

        var order = await _inner.GetByIdAsync(id);
        if (order is not null)
            await _cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(order),
                new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5) });
        return order;
    }
}

Cache read models/DTOs rather than EF entities in practice: entities with private setters and constructors do not round-trip through System.Text.Json without extra configuration, and a deserialized entity is detached from the DbContext. On .NET 9+, HybridCache adds stampede protection over IDistributedCache.

Anti-Patterns

Anti-PatternWhyFix
IQueryable outside repositoryLeaks DB details to applicationReturn IEnumerable<T> or List<T>
async void in ASP.NET CoreUncatchable exceptions, process crashAlways async Task
DbSet<T> in ApplicationCouples to EF CoreUse repository interfaces
Multiple Include() without AsSplitQuery()Cartesian explosion, huge result setsUse AsSplitQuery() or projection
SaveChangesAsync in each handlerNo transactional consistencyOutbox + TransactionBehavior
Direct IConfiguration injectionHard to test, violates ISPIOptions<T> pattern

Security Considerations

  • EF Core raw SQL: always use parameterization, never string interpolation
  • SQL injection: use FromSql($"... {param}") (EF Core 7+, parameterizes interpolations) or FromSqlRaw with explicit DbParameters; never concatenate input into FromSqlRaw
  • Encrypt sensitive columns with a custom ValueConverter backed by the Data Protection API or KMS keys, or use database-level encryption (SQL Server Always Encrypted)
  • Audit logging via EF Core SaveChangesInterceptor or outbox events

Testing Strategies

Unit Testing Pipeline Behaviors

csharp
[Fact]
public async Task ValidationBehavior_ShouldThrowWhenInvalid()
{
    var validator = new InlineValidator<TestRequest>();
    validator.RuleFor(x => x.Value).GreaterThan(0);
    var behavior = new ValidationBehavior<TestRequest, TestResponse>(
        new[] { validator });

    await Assert.ThrowsAsync<ValidationException>(() =>
        behavior.Handle(new TestRequest { Value = -1 }, () => Task.FromResult(new TestResponse()), CancellationToken.None));
}

Integration Testing EF Core

Use WebApplicationFactory<T> with in-memory or TestContainers SQL Server. Seed data in test setup. Verify with Shouldly or FluentAssertions. Use Verify for snapshot testing of complex responses.

Rules

  • MediatR pipeline order: Logging → Validation → Performance → Exception → Transaction.
  • Result pattern at Application boundary — never throw for expected failure paths.
  • Domain events dispatched via MediatR INotification, never directly.
  • Outbox pattern for reliable messaging — write outbox rows in the same transaction as the state change; publish to the broker only after commit (background dispatcher).
  • EF Core: AsNoTracking for reads, AsSplitQuery for multiple includes, ExecuteUpdate for bulk.
  • Caching layer wraps repository — decorated with IDistributedCache.
  • All DB access goes through repository interface — no DbContext in handlers.

References

  • references/cqrs-mediatr.md — CQRS with MediatR
  • references/dotnet-cqrs.md — .NET CQRS Patterns
  • references/dotnet-event-sourcing.md — Event Sourcing in .NET
  • references/dotnet-pipeline-behaviors.md — MediatR Pipeline Behaviors
  • references/dotnet-result-pattern.md — Result Pattern
  • references/ef-core-patterns.md — EF Core Patterns

Handoff

Hand off to backend/dotnet/architecture/SKILL.md for architecture structure or backend/universal/api-response/SKILL.md for API response formatting.

Matgeliwwert Fichieren

De Modell liest dës Dateie bei Bedarf, wärend de Skill gelueden ass. Si ginn als liesbar Dateie bereetgestallt a ginn ni ausgeféiert.

Heefeg gestallte Froen

Wat mécht de KI-Skill Dotnet Patterns?

Use this skill when the user says 'dotnet MediatR pattern', 'dotnet pipeline behavior', 'dotnet Result pattern', 'EF Core performance', 'EF Core outbox', 'dotnet FluentValidation', 'dotnet event sourcing'. Implements .NET application patterns: mediator pipeline behaviors, Result types, EF Core query optimization, outbox, simple event store and caching decorators. Do NOT use for: solution/project structure (dotnet-architecture), non-.NET stacks.

Firwat Dotnet Patterns op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Dotnet Patterns besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt amplaz vun engem Abonnement pro Benotzerplaz. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Dotnet Patterns an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/j4flmao/agent-skills/tree/main/skills/backend/dotnet/patterns an. TypingMind liest d'Datei SKILL.md, bündelt déi zougehéiereg Dateien an installéiert dat Ganzt als Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Dotnet Patterns benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Dotnet Patterns benotzen?

Esou vill Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Dotnet Patterns domat benotzen – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama a méi – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Dotnet Patterns gratis?

Jo. De Skill gëtt vum j4flmao ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbaart Pak vun Instruktiounen, dat engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt en nokënnt a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a keng Lafzäitëmfeld a funktionéiere mat all Modell.

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇