.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
| Layer | Responsibility | Dependencies |
|---|---|---|
| Api | HTTP, endpoints, middleware | Application |
| Application | Business logic, commands/queries | Domain |
| Domain | Entities, business rules | None |
| Infrastructure | Data access, external services | Application |
Entity Framework Core
DbContext Rules
- •Override
SaveChangesAsyncfor audit fields - •Use
ApplyConfigurationsFromAssembly - •Configure with
IEntityTypeConfiguration<T> - •Set
Nullableenable in project
Configuration Best Practices
- •Define max lengths explicitly
- •Create indexes for query fields
- •Configure relationships explicitly
- •Use
HasConversionfor 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
IResulttypes - •Use
TypedResultsfor OpenAPI
Best Practices
- •Inject
ISenderfor 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
| Type | Suffix | Example |
|---|---|---|
| Command | Command | CreateUserCommand |
| Query | Query | GetUserQuery |
| Response | Dto/Response | UserDto |
Best Practices
- •Use
recordfor immutability - •Use
requiredfor mandatory props - •Use
initfor 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/awaitthroughout - •Use FluentValidation
- •Use MediatR for CQRS
- •Separate concerns with layers
DON'T
- •Put business logic in endpoints
- •Use
DateTime.Now(injectIDateTimeService) - •Catch generic
Exception - •Mix sync and async
- •Expose domain entities from API
- •Hardcode connection strings
Code Quality
| Tool | Purpose |
|---|---|
| dotnet format | Code formatting |
| dotnet build /warnaserror | Strict compilation |
| xUnit | Testing |
| FluentAssertions | Test assertions |
| Coverlet | Code coverage |