AgentSkillsCN

Dotnet Patterns

Dotnet 模式

SKILL.md

.NET Backend Patterns Skill

Purpose

Best practices for .NET 10 backend development with ASP.NET Core, Entity Framework Core, and clean architecture.

Auto-Invoke Triggers

  • Creating ASP.NET Core endpoints
  • Working with Entity Framework Core
  • Implementing Dependency Injection
  • Creating DTOs and validation

Project Structure (Clean Architecture)

code
src/
├── MyApp.Api/              # Web API, endpoints
├── MyApp.Application/      # Business logic, CQRS
├── MyApp.Domain/           # Entities, enums
└── MyApp.Infrastructure/   # EF Core, external services
tests/
├── MyApp.Application.Tests/
├── MyApp.Infrastructure.Tests/
└── MyApp.Api.Tests/

Layer Responsibilities

LayerResponsibilityDependencies
ApiHTTP, endpoints, middlewareApplication
ApplicationBusiness logic, commands/queriesDomain
DomainEntities, business rulesNone
InfrastructureData access, external servicesApplication

Entity Framework Core

DbContext Rules

  • Override SaveChangesAsync for audit fields
  • Use ApplyConfigurationsFromAssembly
  • Configure with IEntityTypeConfiguration<T>
  • Set Nullable enable in project

Configuration Best Practices

  • Define max lengths explicitly
  • Create indexes for query fields
  • Configure relationships explicitly
  • Use HasConversion for enums

Query Patterns

  • Use AsNoTracking() for read-only
  • Use Include() sparingly, prefer projections
  • Use AsSplitQuery() for multiple includes
  • Avoid N+1 with proper loading strategy

CQRS with MediatR

Command Pattern

  • One command per action
  • Command = request data
  • Handler = business logic
  • Validator = FluentValidation rules

Query Pattern

  • Queries are read-only
  • Return DTOs, not entities
  • Can skip validation often
  • Optimize for read performance

Pipeline Behaviors

  • ValidationBehavior - Run FluentValidation
  • LoggingBehavior - Log requests/responses
  • PerformanceBehavior - Log slow requests

Minimal API Endpoints

Organization

  • Group by feature/resource
  • Use extension methods: MapUserEndpoints()
  • Return IResult types
  • Use TypedResults for OpenAPI

Best Practices

  • Inject ISender for MediatR
  • Use [FromBody], [FromQuery] explicitly
  • Add .WithName(), .WithTags() for docs
  • Add .Produces<T>() for response types

Dependency Injection

Registration Patterns

  • Use extension methods per layer
  • Register scoped for request-lifetime
  • Register singleton for stateless services
  • Use IOptions<T> for configuration

Common Registrations

csharp
// Application layer
services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(assembly));
services.AddValidatorsFromAssembly(assembly);

// Infrastructure layer
services.AddDbContext<AppDbContext>(options => ...);
services.AddScoped<IRepository<T>, Repository<T>>();

Validation with FluentValidation

Validator Rules

  • One validator per request type
  • Use RuleFor() for each property
  • Use MustAsync() for DB checks
  • Inject repositories for uniqueness checks

Common Validations

  • NotEmpty() - Required fields
  • MaximumLength() - String limits
  • EmailAddress() - Email format
  • Matches() - Regex patterns

DTOs and Records

Naming Convention

TypeSuffixExample
CommandCommandCreateUserCommand
QueryQueryGetUserQuery
ResponseDto/ResponseUserDto

Best Practices

  • Use record for immutability
  • Use required for mandatory props
  • Use init for optional props
  • Don't expose domain entities

Testing

Unit Tests

  • Test handlers in isolation
  • Mock repositories with Moq/NSubstitute
  • Use FluentAssertions for assertions
  • Follow naming: Method_Scenario_Expected

Integration Tests

  • Use WebApplicationFactory
  • Use in-memory database
  • Override DI registrations
  • Test full request pipeline

Best Practices

DO

  • Use record types for DTOs
  • Use nullable reference types
  • Use async/await throughout
  • Use FluentValidation
  • Use MediatR for CQRS
  • Separate concerns with layers

DON'T

  • Put business logic in endpoints
  • Use DateTime.Now (inject IDateTimeService)
  • Catch generic Exception
  • Mix sync and async
  • Expose domain entities from API
  • Hardcode connection strings

Code Quality

ToolPurpose
dotnet formatCode formatting
dotnet build /warnaserrorStrict compilation
xUnitTesting
FluentAssertionsTest assertions
CoverletCode coverage