dotnet-patterns
Use when the user asks about MediatR pipeline behaviors, the Result pattern in C#, FluentValidation, EF Core performance (AsNoTracking, ExecuteUpdate), EF…
от j4flmao★ 47 звёзд на GitHub
Установить dotnet-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
.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
| Order | Behavior | Purpose |
|---|---|---|
| 1 | LoggingBehavior | Log request start/end with timing |
| 2 | ValidationBehavior | Validate before processing |
| 3 | PerformanceBehavior | Warn if > threshold (500ms) |
| 4 | UnhandledExceptionBehavior | Catch and wrap unhandled |
| 5 | TransactionBehavior | Wrap in DB transaction |
Pipeline behaviors run in registration order (first added = outer wrapper, runs first).
FluentValidation vs Data Annotations
| Criterion | FluentValidation | Data Annotations |
|---|---|---|
| Separation | External to model | On model properties |
| Conditional rules | Yes (When/Unless) | Limited |
| Cross-property | Yes (Must) | No |
| DI support | Yes (inject services) | No |
| Testability | Easy (validator per model) | Requires model instantiation |
Decision: Complex validation rules → FluentValidation. Simple non-null/range checks → Data Annotations.
Workflow
Step 1: MediatR Pipeline Behaviors
// 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
// 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"
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- references/cqrs-mediatr.md
- references/dotnet-cqrs.md
- references/dotnet-event-sourcing.md
- references/dotnet-pipeline-behaviors.md
- references/dotnet-result-pattern.md
- references/ef-core-patterns.md
FAQ
Что делает скилл dotnet-patterns?
Use when the user asks about MediatR pipeline behaviors, the Result pattern in C#, FluentValidation, EF Core performance (AsNoTracking, ExecuteUpdate), EF Core outbox or dotnet CQRS handlers. Produces C# implementations of these patterns. Not for solution layout (use dotnet-architecture).
Как установить скилл dotnet-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл dotnet-patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
frontend-design
AnthropicGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making…
webapp-testing
AnthropicToolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing…
brand-guidelines
AnthropicApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand…
web-artifacts-builder
AnthropicSuite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use…