NET applications. NET code — DI, async, or general conventions.
Frontmatter
name dotnet-patterns
description Idiomatic C# and .NET patterns, conventions, dependency injection, async/await, and best practices for building robust, maintainable .NET applications. Use when writing or reviewing C# / .NET code — DI, async, or general conventions. .NET Development Patterns
Idiomatic C# and .NET patterns for building robust, performant, and maintainable applications.
When to Activate
Writing new C# code
Reviewing C# code
Refactoring existing .NET applications
Designing service architectures with ASP.NET Core
Core Principles
1. Prefer Immutability
Use records and init-only properties for data models. Mutability should be an explicit, justified choice.
public sealed record Money (decimal Amount, string Currency ) ;
public sealed class CreateOrderRequest
{
public required string CustomerId { get ; init ; }
public required IReadOnlyList<OrderItem> Items { get ; init ; }
}
public class Order
{
public string CustomerId { get ; set ; }
public List<OrderItem> Items { get ; set ; }
}
2. Explicit Over Implicit
Be clear about nullability, access modifiers, and intent.
public sealed class UserService
{
private readonly IUserRepository _ repository;
private readonly ILogger<UserService> _ logger;
public UserService (IUserRepository repository, ILogger<UserService> logger )
{
_ repository = repository ?? throw new ArgumentNullException(nameof (repository));
_ logger = logger ?? throw new ArgumentNullException(nameof (logger));
}
public async Task<User?> FindByIdAsync(Guid id, CancellationToken cancellationToken)
{
return await _ repository.FindByIdAsync(id, cancellationToken);
}
}
3. Depend on Abstractions
Use interfaces for service boundaries. Register via DI container.
public interface IOrderRepository
{
Task<Order?> FindByIdAsync(Guid id, CancellationToken cancellationToken);
Task<IReadOnlyList<Order>> FindByCustomerAsync(string customerId, CancellationToken cancellationToken);
Task AddAsync (Order order, CancellationToken cancellationToken ) ;
}
builder.Services.AddScoped<IOrderRepository, SqlOrderRepository>();
Async/Await Patterns
Proper Async Usage
public async Task<OrderSummary> GetOrderSummaryAsync (
Guid orderId,
CancellationToken cancellationToken )
{
var order = await _ repository.FindByIdAsync(orderId, cancellationToken)
?? throw new NotFoundException($"Order {orderId} not found" );
var customer = await _ customerService.GetAsync(order.CustomerId, cancellationToken);
return new OrderSummary(order, customer);
}
public OrderSummary GetOrderSummary (Guid orderId )
{
var order = _ repository.FindByIdAsync(orderId, CancellationToken.None).Result;
return new OrderSummary(order);
}
Parallel Async Operations
public async Task<DashboardData> LoadDashboardAsync (CancellationToken cancellationToken )
{
var ordersTask = _ orderService.GetRecentAsync(cancellationToken);
var metricsTask = _ metricsService.GetCurrentAsync(cancellationToken);
var alertsTask = _ alertService.GetActiveAsync(cancellationToken);
await Task.WhenAll(ordersTask, metricsTask, alertsTask);
return new DashboardData(
Orders: await ordersTask,
Metrics: await metricsTask,
Alerts: await alertsTask);
}
Options Pattern
Bind configuration sections to strongly-typed objects.
public sealed class SmtpOptions
{
public const string SectionName = "Smtp" ;
public required string Host { get ; init ; }
public required int Port { get ; init ; }
public required string Username { get ; init ; }
public bool UseSsl { get ; init ; } = true ;
}
builder.Services.Configure<SmtpOptions>(
builder.Configuration.GetSection(SmtpOptions.SectionName));
public class EmailService (IOptions<SmtpOptions> options )
{
private readonly SmtpOptions _ smtp = options.Value;
}
Result Pattern
Return explicit success/failure instead of throwing for expected failures.
public sealed record Result <T >
{
public bool IsSuccess { get ; }
public T? Value { get ; }
public string ? Error { get ; }
private Result (T value ) { IsSuccess = true ; Value = value ; }
private Result (string error ) { IsSuccess = false ; Error = error; }
public static Result<T> Success (T value ) => new (value );
public static Result<T> Failure (string error ) => new (error);
}
public async Task<Result<Order>> PlaceOrderAsync(CreateOrderRequest request)
{
if (request.Items.Count == 0 )
return Result<Order>.Failure("Order must contain at least one item" );
var order = Order.Create(request);
await _ repository.AddAsync(order, CancellationToken.None);
return Result<Order>.Success(order);
}
Repository Pattern with EF Core
public sealed class SqlOrderRepository : IOrderRepository
{
private readonly AppDbContext _ db;
public SqlOrderRepository (AppDbContext db ) => _ db = db;
public async Task<Order?> FindByIdAsync(Guid id, CancellationToken cancellationToken)
{
return await _ db.Orders
.Include(o => o.Items)
.AsNoTracking()
.FirstOrDefaultAsync(o => o.Id == id, cancellationToken);
}
public async Task<IReadOnlyList<Order>> FindByCustomerAsync(
string customerId,
CancellationToken cancellationToken)
{
return await _ db.Orders
.Where(o => o.CustomerId == customerId)
.OrderByDescending(o => o.CreatedAt)
.AsNoTracking()
.ToListAsync(cancellationToken);
}
public async Task AddAsync (Order order, CancellationToken cancellationToken )
{
_ db.Orders.Add(order);
await _ db.SaveChangesAsync(cancellationToken);
}
}
Middleware and Pipeline
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 context )
{
var stopwatch = Stopwatch.StartNew();
try
{
await _ next(context);
}
finally
{
stopwatch.Stop();
_ logger.LogInformation(
"Request {Method} {Path} completed in {ElapsedMs}ms with status {StatusCode}" ,
context.Request.Method,
context.Request.Path,
stopwatch.ElapsedMilliseconds,
context.Response.StatusCode);
}
}
}
Minimal API Patterns
var orders = app.MapGroup("/api/orders" )
.RequireAuthorization()
.WithTags("Orders" );
orders.MapGet("/{id:guid}" , async (
Guid id,
IOrderRepository repository,
CancellationToken cancellationToken) =>
{
var order = await repository.FindByIdAsync(id, cancellationToken);
return order is not null
? TypedResults.Ok(order)
: TypedResults.NotFound();
});
orders.MapPost("/" , async (
CreateOrderRequest request,
IOrderService service,
CancellationToken cancellationToken) =>
{
var result = await service.PlaceOrderAsync(request, cancellationToken);
return result.IsSuccess
? TypedResults.Created($"/api/orders/{result.Value!.Id} " , result.Value)
: TypedResults.BadRequest(result.Error);
});
Guard Clauses
public async Task<ProcessResult> ProcessPaymentAsync (
PaymentRequest request,
CancellationToken cancellationToken )
{
ArgumentNullException.ThrowIfNull(request);
if (request.Amount <= 0 )
throw new ArgumentOutOfRangeException(nameof (request.Amount), "Amount must be positive" );
if (string .IsNullOrWhiteSpace(request.Currency))
throw new ArgumentException("Currency is required" , nameof (request.Currency));
var gateway = _ gatewayFactory.Create(request.Currency);
return await gateway.ChargeAsync(request, cancellationToken);
}
Anti-Patterns to Avoid
Anti-Pattern Fix async void methodsReturn Task (except event handlers) .Result or .Wait()Use await catch (Exception) { }Handle or rethrow with context new Service() in constructorsUse constructor injection public fieldsUse properties with appropriate accessors dynamic in business logicUse generics or explicit types Mutable static state Use DI scoping or ConcurrentDictionary string.Format in loopsUse StringBuilder or interpolated string handlers