Skip to content
Skillpedia
APIs & servers (backend)41k Β· #6693

dotnet-backend-patterns

What it does

This skill helps you understand and apply best practices for building robust systems in .NET (C#). It covers everything from code organization to handling asynchronous tasks and configuring your application.

When to use it

  • βœ“When starting a new .NET backend project.
  • βœ“When reviewing C# code for quality.
  • βœ“When designing API and service architectures.

Skill link

https://github.com/wshobson/agents/blob/main/plugins/dotnet-contribution/skills/dotnet-backend-patterns/SKILL.md

Copy it and paste it into your AI (Claude, ChatGPT or Cursor), asking it to follow the instructions.

How to use

The easiest way: copy the message and paste it into your AI. It reads the skill and follows the instructions.

Ready-to-paste message

Use this skill to help me: https://github.com/wshobson/agents/blob/main/plugins/dotnet-contribution/skills/dotnet-backend-patterns/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
Want your AI to find skills like this on its own?Install the free Skillpedia MCP: one line, and it searches 15,000+ skills before each task.Install in 1 minute β†’

Example of what to ask your AI

β€œHow can I structure my .NET project following clean architecture?”

5 new skills a week. 1 minute to read.

How it works

The skill explains concepts like folder structure (Clean Architecture), how to inject dependencies (Dependency Injection) to make code more flexible, and how to use `async/await` to handle time-consuming operations without freezing the system.

Technical content (original SKILL.md)

Original text by the author, straight from GitHub.

.NET Backend Development Patterns

Master C#/.NET patterns for building production-grade APIs, MCP servers, and enterprise backends with modern best practices (2024/2025).

When to Use This Skill

  • Developing new .NET Web APIs or MCP servers
  • Reviewing C# code for quality and performance
  • Designing service architectures with dependency injection
  • Implementing caching strategies with Redis
  • Writing unit and integration tests
  • Optimizing database access with EF Core or Dapper
  • Configuring applications with IOptions pattern
  • Handling errors and implementing resilience patterns

Core Concepts

1. Project Structure (Clean Architecture)

src/
β”œβ”€β”€ Domain/                     # Core business logic (no dependencies)
β”‚   β”œβ”€β”€ Entities/
β”‚   β”œβ”€β”€ Interfaces/
β”‚   β”œβ”€β”€ Exceptions/
β”‚   └── ValueObjects/
β”œβ”€β”€ Application/                # Use cases, DTOs, validation
β”‚   β”œβ”€β”€ Services/
β”‚   β”œβ”€β”€ DTOs/
β”‚   β”œβ”€β”€ Validators/
β”‚   └── Interfaces/
β”œβ”€β”€ Infrastructure/             # External implementations
β”‚   β”œβ”€β”€ Data/                   # EF Core, Dapper repositories
β”‚   β”œβ”€β”€ Caching/                # Redis, Memory cache
β”‚   β”œβ”€β”€ External/               # HTTP clients, third-party APIs
β”‚   └── DependencyInjection/    # Service registration
└── Api/                        # Entry point
    β”œβ”€β”€ Controllers/            # Or MinimalAPI endpoints
    β”œβ”€β”€ Middleware/
    β”œβ”€β”€ Filters/
    └── Program.cs

2. Dependency Injection Patterns

// Service registration by lifetime
public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddApplicationServices(
        this IServiceCollection services,
        IConfiguration configuration)
    {
        // Scoped: One instance per HTTP request
        services.AddScoped<IProductService, ProductService>();
        services.AddScoped<IOrderService, OrderService>();

        // Singleton: One instance for app lifetime
        services.AddSingleton<ICacheService, RedisCacheService>();
        services.AddSingleton<IConnectionMultiplexer>(_ =>
            ConnectionMultiplexer.Connect(configuration["Redis:Connection"]!));

        // Transient: New instance every time
        services.AddTransient<IValidator<CreateOrderRequest>, CreateOrderValidator>();

        // Options pattern for configuration
        services.Configure<CatalogOptions>(configuration.GetSection("Catalog"));
        services.Configure<RedisOptions>(configuration.GetSection("Redis"));

        // Factory pattern for conditional creation
        services.AddScoped<IPriceCalculator>(sp =>
        {
            var options = sp.GetRequiredService<IOptions<PricingOptions>>().Value;
            return options.UseNewEngine
                ? sp.GetRequiredService<NewPriceCalculator>()
                : sp.GetRequiredService<LegacyPriceCalculator>();
        });

        // Keyed services (.NET 8+)
        services.AddKeyedScoped<IPaymentProcessor, StripeProcessor>("stripe");
        services.AddKeyedScoped<IPaymentProcessor, PayPalProcessor>("paypal");

        return services;
    }
}

// Usage with keyed services
public class CheckoutService
{
    public CheckoutService(
        [FromKeyedServices("stripe")] IPaymentProcessor stripeProcessor)
    {
        _processor = stripeProcessor;
    }
}

3. Async/Await Patterns

// βœ… CORRECT: Async all the way down
public async Task<Product> GetProductAsync(string id, CancellationToken ct = default)
{
    return await _repository.GetByIdAsync(id, ct);
}

// βœ… CORRECT: Parallel execution with WhenAll
public async Task<(Stock, Price)> GetStockAndPriceAsync(
    string productId,
    CancellationToken ct = default)
{
    var stockTask = _stockService.GetAsync(productId, ct);
    var priceTask = _priceService.GetAsync(productId, ct);

    await Task.WhenAll(stockTask, priceTask);

    return (await stockTask, await priceTask);
}

// βœ… CORRECT: ConfigureAwait in libraries
public async Task<T> LibraryMethodAsync<T>(CancellationToken ct = default)
{
    var result = await _httpClient.GetAsync(url, ct).ConfigureAwait(false);
    return await result.Content.ReadFromJsonAsync<T>(ct).ConfigureAwait(false);
}

// βœ… CORRECT: ValueTask for hot paths with caching
public ValueTask<Product?> GetCachedProductAsync(string id)
{
    if (_cache.TryGetValue(id, out Product? product))
        return ValueTask.FromResult(product);

    return new ValueTask<Product?>(GetFromDatabaseAsync(id));
}

// ❌ WRONG: Blocking on async (deadlock risk)

…
FAQ

What is 'Dependency Injection'?

It's a technique where dependencies (other pieces of code a component needs) are provided from the outside, rather than being created within the component itself. This makes the code easier to test and modify.

Why use 'async/await'?

So your program can do other things while waiting for long operations, like accessing a database or calling an external service. This improves responsiveness and performance.

What is 'Clean Architecture'?

It's a way of organizing code into layers, separating responsibilities. The idea is to keep the core business logic isolated from external details like databases or user interfaces.

Details

Original description by the author

Master C#/.NET backend development patterns for building robust APIs, MCP servers, and enterprise applications. Covers async/await, dependency injection, Entity Framework Core, Dapper, configuration, caching, and testing with xUnit. Use when developing .NET backends, reviewing C# code, or designing API architectures.

repo: wshobson/agents

Popularity

GitHub stars
41k
Ranking position
#6693
License
MIT
Updated
10/15/2026

Is this skill useful?

0

Sign in to vote.

Comments

  • …

More skills from this repository

Similar skills