agentleFS
mohammed-shaker-devmohammed-shaker-dev/dotnet-claude-skills/skills/architecture/SKILL.md

dotnet-architecture

Skill1 starsChanged 10 months agoMITView on GitHub

Architecture decision guidance for .NET projects. Helps choose between Clean Architecture, CQRS, microservices, and other patterns based on project requirements. Use when designing system architecture, choosing patterns, or structuring new projects.

4 other projects use a version of this.

Adopted by

Most recently taken up by

  • Other versions4 projects use a version of this.

    Word for word · 0

    None found.

    Edited · 0

    None found.

    Wrote their own version · 4

    1. Postpartum-genushyacinthus29/dotnet-skills★ 12same name
    2. dprakash2101/dotnet-production-agent-skills★ 4same name
    3. emaginebr/AvaBot★ 2same name
    4. landim32/awesome-ai-skills★ 1same name

    How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.

  • In this repository3 other files it gives its agents.

The file

Files
SKILL.md

.NET Architecture Decision Skill

This skill helps make informed architecture decisions for .NET projects based on requirements, team size, and complexity.

Core Philosophy

The mark of a senior architect is knowing when NOT to over-engineer.

Simple features need simple structures. Complex systems need complex architecture. Never apply Clean Architecture to a 50-line utility.


Architecture Decision Framework

Step 1: Assess Requirements

Ask these questions:

  1. What is the business domain complexity?
  2. What are the scalability requirements?
  3. What is the team size and expertise?
  4. What is the expected lifetime of the project?
  5. Are there specific non-functional requirements (performance, security)?

Step 2: Choose Architecture Tier

ComplexityStructureUse When
Tier 1: SimpleSingle projectUtilities, MCP servers, simple APIs, demos
Tier 2: Medium2-3 projectsFeature-complete apps, RAG systems, real-time apps
Tier 3: ComplexFull Clean ArchitectureEnterprise systems, microservices, DDD

Step 3: Select Patterns

Match patterns to problems:

ProblemPatternWhen to Use
Data access abstractionRepositoryAlways (unless very simple CRUD)
Expected failure handlingResult PatternComplex business logic
Complex queriesSpecificationMany query variations
Separate read/write needsCQRSDifferent read/write models
Audit trail neededEvent SourcingFinancial, compliance systems
Multiple bounded contextsMicroservicesLarge teams, independent deployment

Architecture Patterns

Tier 1: Simple Structure

Use for: MCP servers, utilities, single-feature demos, CLI tools

ProjectName/
├── README.md
├── src/
│   └── ProjectName/
│       ├── Program.cs
│       ├── Services/
│       ├── Models/
│       └── appsettings.json
├── tests/
│   └── ProjectName.Tests/
├── Dockerfile
└── .github/workflows/ci.yml

Characteristics:

  • Single project, no layers
  • Direct service classes
  • Simple DI registration
  • Inline configuration
  • Basic error handling

Example: MCP Server

// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IDatabaseService, DatabaseService>();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();
app.MapToolEndpoints();
app.Run();

// Services/DatabaseService.cs
public sealed class DatabaseService(IDbConnection db) : IDatabaseService
{
    public async Task<IEnumerable<dynamic>> QueryAsync(string sql)
        => await db.QueryAsync(sql);
}

Tier 2: Medium Structure

Use for: Feature-complete applications, bounded contexts, vertical slices

ProjectName/
├── README.md
├── src/
│   ├── ProjectName.Api/           # Endpoints + DI setup
│   ├── ProjectName.Core/          # Business logic + Interfaces
│   └── ProjectName.Infrastructure/ # Data access + External services
├── tests/
│   ├── ProjectName.Core.Tests/
│   └── ProjectName.Integration.Tests/
├── docker-compose.yml
└── .github/workflows/ci.yml

Dependency Flow:

Api → Core ← Infrastructure
         ↑
    (depends on)

Characteristics:

  • 2-3 projects with clear responsibilities
  • Repository pattern
  • MediatR for command/query separation (optional)
  • Proper configuration management
  • Integration tests with Testcontainers

Example Structure:

// Core/Interfaces/IOrderRepository.cs
public interface IOrderRepository
{
    Task<Order?> GetByIdAsync(Guid id, CancellationToken ct);
    Task AddAsync(Order order, CancellationToken ct);
}

// Core/Services/OrderService.cs
public sealed class OrderService(IOrderRepository repository)
{
    public async Task<Order?> GetOrderAsync(Guid id, CancellationToken ct)
        => await repository.GetByIdAsync(id, ct);
}

// Infrastructure/Repositories/OrderRepository.cs
public sealed class OrderRepository(AppDbContext db) : IOrderRepository
{
    public async Task<Order?> GetByIdAsync(Guid id, CancellationToken ct)
        => await db.Orders.FindAsync([id], ct);
}

// Api/Endpoints/OrderEndpoints.cs
public static class OrderEndpoints
{
    public static void MapOrderEndpoints(this IEndpointRouteBuilder app)
    {
        app.MapGet("/orders/{id}", GetOrder);
    }
}

Tier 3: Complex Structure (Clean Architecture)

Use for: Enterprise systems, microservices, DDD implementations

ProjectName/
├── README.md
├── docs/
│   ├── architecture.md
│   └── adr/
├── src/
│   ├── Domain/
│   │   ├── Entities/
│   │   ├── ValueObjects/
│   │   ├── Events/
│   │   └── Interfaces/
│   ├── Application/
│   │   ├── Commands/
│   │   ├── Queries/
│   │   ├── DTOs/
│   │   └── Validators/
│   ├── Infrastructure/
│   │   ├── Persistence/
│   │   ├── Messaging/
│   │   └── ExternalServices/
│   └── WebApi/
│       ├── Endpoints/
│       └── Middleware/
├── tests/
│   ├── Domain.Tests/
│   ├── Application.Tests/
│   └── Integration.Tests/
├── docker-compose.yml
└── .github/workflows/ci.yml

Dependency Flow:

     WebApi
        ↓
   Application
        ↓
     Domain (no dependencies)
        ↑
  Infrastructure (implements Domain interfaces)

Key Principles:

  1. Domain has zero external dependencies
  2. Application depends only on Domain
  3. Infrastructure implements Domain interfaces
  4. WebApi orchestrates everything

Pattern Implementations

Repository Pattern

// Domain/Interfaces/IRepository.cs
public interface IRepository<T> where T : Entity
{
    Task<T?> GetByIdAsync(Guid id, CancellationToken ct = default);
    Task<IReadOnlyList<T>> GetAllAsync(CancellationToken ct = default);
    Task AddAsync(T entity, CancellationToken ct = default);
    Task UpdateAsync(T entity, CancellationToken ct = default);
    Task DeleteAsync(T entity, CancellationToken ct = default);
}

// Domain/Interfaces/IOrderRepository.cs
public interface IOrderRepository : IRepository<Order>
{
    Task<IReadOnlyList<Order>> GetByCustomerIdAsync(
        Guid customerId, 
        CancellationToken ct = default);
}

Result Pattern

// Domain/Common/Result.cs
public sealed class Result<T>
{
    public bool IsSuccess { get; }
    public T? Value { get; }
    public Error? Error { get; }
    
    private Result(bool isSuccess, T? value, Error? error)
        => (IsSuccess, Value, Error) = (isSuccess, value, error);
    
    public static Result<T> Success(T value) => new(true, value, null);
    public static Result<T> Failure(Error error) => new(false, default, error);
    
    public TResult Match<TResult>(
        Func<T, TResult> onSuccess,
        Func<Error, TResult> onFailure)
        => IsSuccess ? onSuccess(Value!) : onFailure(Error!);
}

public sealed record Error(string Code, string Message)
{
    public static Error NotFound(string entity, Guid id) 
        => new("NotFound", $"{entity} with ID {id} was not found");
    
    public static Error Validation(string message)
        => new("Validation", message);
}

CQRS with MediatR

// Application/Commands/CreateOrderCommand.cs
public sealed record CreateOrderCommand(
    Guid CustomerId,
    List<OrderItemDto> Items) : IRequest<Result<OrderDto>>;

public sealed class CreateOrderCommandValidator 
    : AbstractValidator<CreateOrderCommand>
{
    public CreateOrderCommandValidator()
    {
        RuleFor(x => x.CustomerId).NotEmpty();
        RuleFor(x => x.Items).NotEmpty();
    }
}

public sealed class CreateOrderCommandHandler(
    IOrderRepository repository,
    IUnitOfWork unitOfWork)
    : IRequestHandler<CreateOrderCommand, Result<OrderDto>>
{
    public async Task<Result<OrderDto>> Handle(
        CreateOrderCommand request,
        CancellationToken ct)
    {
        var order = Order.Create(request.CustomerId, request.Items);
        
        await repository.AddAsync(order, ct);
        await unitOfWork.SaveChangesAsync(ct);
        
        return Result<OrderDto>.Success(order.ToDto());
    }
}

// Application/Queries/GetOrderQuery.cs
public sealed record GetOrderQuery(Guid OrderId) : IRequest<OrderDto?>;

public sealed class GetOrderQueryHandler(IAppDbContext db)
    : IRequestHandler<GetOrderQuery, OrderDto?>
{
    public async Task<OrderDto?> Handle(
        GetOrderQuery request,
        CancellationToken ct)
    {
        return await db.Orders
            .AsNoTracking()
            .Where(o => o.Id == request.OrderId)
            .Select(o => new OrderDto(o.Id, o.Total, o.Status))
            .FirstOrDefaultAsync(ct);
    }
}

Domain Events

// Domain/Events/IDomainEvent.cs
public interface IDomainEvent
{
    DateTime OccurredAt { get; }
}

// Domain/Events/OrderCreatedEvent.cs
public sealed record OrderCreatedEvent(
    Guid OrderId,
    Guid CustomerId,
    decimal Total) : IDomainEvent
{
    public DateTime OccurredAt { get; } = DateTime.UtcNow;
}

// Domain/Common/Entity.cs
public abstract class Entity
{
    private readonly List<IDomainEvent> _domainEvents = [];
    
    public IReadOnlyCollection<IDomainEvent> DomainEvents 
        => _domainEvents.AsReadOnly();
    
    protected void RaiseDomainEvent(IDomainEvent domainEvent)
        => _domainEvents.Add(domainEvent);
    
    public void ClearDomainEvents() => _domainEvents.Clear();
}

// Domain/Entities/Order.cs
public sealed class Order : Entity
{
    public static Order Create(Guid customerId, List<OrderItem> items)
    {
        var order = new Order
        {
            Id = Guid.NewGuid(),
            CustomerId = customerId,
            Items = items,
            CreatedAt = DateTime.UtcNow
        };
        
        order.RaiseDomainEvent(new OrderCreatedEvent(
            order.Id, 
            order.CustomerId, 
            order.Total));
        
        return order;
    }
}

Decision Matrix

FactorTier 1 (Simple)Tier 2 (Medium)Tier 3 (Complex)
Business logicMinimalModerateComplex
Database needsNone/SQLiteSingle DBMultiple DBs
External integrations1-23-5Many
Team size12-45+
Lines of code<1,0001,000-10,00010,000+
Time to build1-2 days3-5 days5+ days
Maintenance expectedMinimalModerateLong-term

Anti-Patterns to Avoid

Over-Engineering

// ❌ Factory for simple object
public interface IOrderFactory
{
    Order Create(CreateOrderRequest request);
}

public class OrderFactory : IOrderFactory
{
    public Order Create(CreateOrderRequest request)
        => new Order { /* simple mapping */ };
}

// ✅ Direct creation for simple cases
var order = new Order
{
    Id = Guid.NewGuid(),
    CustomerId = request.CustomerId
};

Premature Abstraction

// ❌ Interface for one implementation
public interface IOrderHelper { }
public class OrderHelper : IOrderHelper { }

// ✅ Make it concrete until you need abstraction
public class OrderHelper { }

Wrong Pattern for the Job

// ❌ CQRS for simple CRUD
public record GetUserByIdQuery(int Id) : IRequest<User>;
public class GetUserByIdQueryHandler : IRequestHandler<...> { }

// ✅ Direct repository for simple CRUD
var user = await _userRepository.GetByIdAsync(id);

Quick Reference

When to Use Each Pattern

PatternUse WhenDon't Use When
RepositoryNeed to abstract data accessSimple scripts, utilities
ResultExpected failures in business logicInfrastructure code
CQRSDifferent read/write modelsSimple CRUD
Event SourcingAudit trail requiredSimple state storage
Domain EventsCross-aggregate communicationWithin same aggregate
SpecificationComplex, reusable queriesSimple queries

NuGet Packages by Tier

Tier 1:

  • Dapper, Serilog, Swashbuckle

Tier 2 (add):

  • MediatR, FluentValidation, EF Core, Testcontainers

Tier 3 (add):

  • MassTransit, Marten, OpenTelemetry

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.