Chuyển đến nội dung
Skillpedia
API và máy chủ (backend)41k · #6693

dotnet-backend-patterns

Skill này làm gì

Skill này giúp bạn hiểu và áp dụng các thực hành tốt nhất để xây dựng hệ thống vững chắc bằng .NET (C#). Nội dung bao gồm từ cách tổ chức code đến xử lý tác vụ bất đồng bộ và cấu hình ứng dụng.

Khi nào nên dùng

  • ✓Khi bạn bắt đầu một dự án backend .NET mới.
  • ✓Khi bạn rà soát code C# để đảm bảo chất lượng.
  • ✓Khi bạn thiết kế kiến trúc API và dịch vụ.

Liên kết skill

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

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/wshobson/agents/blob/main/plugins/dotnet-contribution/skills/dotnet-backend-patterns/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để tổ chức dự án .NET của tôi theo kiến trúc sạch (clean architecture)?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Skill giải thích các khái niệm như cấu trúc thư mục (Clean Architecture), cách tiêm phụ thuộc (Dependency Injection) để code linh hoạt hơn, và cách dùng `async/await` để xử lý các thao tác tốn thời gian mà không làm treo hệ thống.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

.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)

…
Câu hỏi thường gặp

“Dependency Injection” là gì?

Đó là kỹ thuật cung cấp các phụ thuộc (những đoạn code khác mà một thành phần cần) từ bên ngoài, thay vì tự tạo chúng bên trong thành phần. Cách này giúp code dễ kiểm thử và chỉnh sửa hơn.

Tại sao dùng “async/await”?

Để chương trình của bạn có thể làm việc khác trong khi chờ các thao tác dài, như truy cập cơ sở dữ liệu hoặc gọi một dịch vụ bên ngoài. Điều này giúp cải thiện khả năng phản hồi và hiệu năng.

“Clean Architecture” là gì?

Đó là cách tổ chức code thành các lớp, tách biệt các trách nhiệm. Ý tưởng là giữ logic nghiệp vụ cốt lõi tách biệt khỏi các chi tiết bên ngoài như cơ sở dữ liệu hay giao diện người dùng.

Chi tiết

Mô tả gốc của tác giả

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

Độ phổ biến

Sao GitHub
41k
Vị trí xếp hạng
#6693
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự