Skip to content
Skills Library
Programming · Building & coding

csharp-dotnet

/csharp-dotnet

C# and .NET patterns for OpenClaw. Triggers when writing C#, implementing .NET APIs, working with EF Core, or making architecture decisions in .NET projects. Use for: Clean Architecture, dependency injection, async patterns, Result pattern, Minimal APIs, EF Core queries, and unit testing in C#.

Repository
lucy-ai ↗
Licence
MIT
Last repository change
31.07.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 31.07.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

C# and .NET patterns for OpenClaw. Triggers when writing C#, implementing .NET APIs, working with EF Core, or making architecture decisions in .NET projects. Use for: Clean Architecture, dependency injection, async patterns, Result pattern, Minimal APIs, EF Core queries, and unit testing in C#.

Original author description

C# and .NET patterns for OpenClaw. Triggers when writing C#, implementing .NET APIs, working with EF Core, or making architecture decisions in .NET projects. Use for: Clean Architecture, dependency injection, async patterns, Result pattern, Minimal APIs, EF Core queries, and unit testing in C#.

How it works

  1. Clean Architecture (REQUIRED)
  2. Dependency Injection (REQUIRED)
  3. Entity Framework Core (REQUIRED)
  4. Async/Await (REQUIRED)
  5. Result Pattern (REQUIRED for business logic)
  6. Error Handling (REQUIRED)
  7. Minimal APIs (PREFERRED over Controllers for new APIs)
  8. Record Types
  9. LINQ Patterns
  10. Testing
Original SKILL.md headings · 313 lines, 820 words
SKILL.md preview
---
name: csharp-dotnet
description: >
  C# and .NET patterns for OpenClaw. Triggers when writing C#, implementing .NET APIs, working with EF Core, or making architecture decisions in .NET projects.
  Use for: Clean Architecture, dependency injection, async patterns, Result pattern, Minimal APIs, EF Core queries, and unit testing in C#.
metadata:
  author: lucy-camilo
  version: "1.0"
---

## Clean Architecture (REQUIRED)

```
src/
├── Domain/           # Entities, value objects, interfaces — NO dependencies
├── Application/      # Use cases, DTOs, repository interfaces
├── Infrastructure/   # EF Core, external services
└── API/             # Controllers, Minimal APIs, middleware
```

**Rule:** Dependencies only point inward. Domain knows nothing.

---

## Dependency Injection (REQUIRED)

```csharp
// ALWAYS: Interface-based DI
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IUserService, UserService>();

// DbContext always Scoped
builder.Services.AddDbContext<AppDbContext>(opts =>
    opts.UseSqlServer(connectionString));

// AutoMapper
builder.Services.AddAutoMapper(typeof(MappingProfile));
```

| Lifetime | Use |
|---|---|
| **Scoped** | DbContext, Repositories, Services (per-request state) |
| **Transient** | Lightweight stateless services |
| **Singleton** | Config, global caching |

---

## Entity Framework Core (REQUIRED)

### DbContext

```csharp
public class AppDbContext : DbContext
{
    public DbSet<User> Users => Set<User>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>(entity =>
        {
            entity.HasKey(e => e.Id);
            entity.Property(e => e.Email).IsRequired().HasMaxLength(256);
            entity.HasIndex(e => e.Email).IsUnique();
        });

        modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
    }
}
```

### Query patterns

```csharp
// Eager loading — NO lazy loading in production
var users = await context.Users
    .Include(u => u.Orders)
    .Where(u => u.IsActive)
    .Select(u => new UserDto { Id = u.Id, Email = u.Email })
    .ToListAsync(ct);
```

---

## Async/Await (REQUIRED)

```csharp
// ALWAYS async at API boundary
[HttpGet("{id}")]
public async Task<ActionResult<UserDto>> GetById(int id, CancellationToken ct)
{
    var user = await _service.GetByIdAsync(id, ct);
    return user is null ? NotFound() : Ok(user);
}

// CancellationToken on every async operation
public async Task<UserDto?> GetByIdAsync(int id, CancellationToken ct = default)
{
    ct.ThrowIfCancellationRequested();
    return await _repository.GetByIdAsync(id, ct);
}
```

---

## Result Pattern (REQUIRED for business logic)

```csharp
public record Result<T>(T? Value, Error? Error)
{
    public bool IsSuccess => Error is null;
    public bool IsFailure => !IsSuccess;

    public static Result<T> Success(T value) => new(value, null);
    public static Result<T> Failure(Error error) => new(default, error);
}

public record Error(string Code, string Message);

// Usage
public async Task<Result<OrderDto>> CreateOrderAsync(CreateOrderCommand cmd, CancellationToken ct)
{
    if (!await _userRepository.ExistsAsync(cmd.UserId, ct))
        return Result<OrderDto>.Failure(new Error("USER_NOT_FOUND", "User does not exist"));

    var order = await _repository.CreateAsync(cmd, ct);
    return Result<OrderDto>.Success(_mapper.Map<OrderDto>(order));
}
```

---

## Error Handling (REQUIRED)

```csharp
// NEVER swallow exceptions
try { }
catch (Exception ex)
{
    _logger.LogError(ex, "Error processing request {Id}", requestId);
    throw;  // Always rethrow
}

// Global exception handler
app.UseExceptionHandler(appBuilder =>
{
    appBuilder.Run(async context =>
    {
        var exception = context.Features.Get<IExceptionHandlerFeature>()?.Error;
        var (statusCode, message) = exception switch
        {
            ValidationException => (400, exception.Message),
            NotFoundException => (404, exception.Message),
            _ => (500, "An error occurred")
        };

        context.Response.StatusCode = statusCode;
        await context.Response.WriteAsJsonAsync(new { error = message });
    });
});
```

---

## Minimal APIs (PREFERRED over Controllers for new APIs)

```csharp
public static class UserEndpoints
{
    public static void MapUserEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/api/users").WithTags("Users");

        group.MapGet("/", async (IUserService svc, CancellationToken ct) =>
            Results.Ok(await svc.GetAllAsync(ct)));

        group.MapGet("/{id:int}", async (int id, IUserService svc, CancellationToken ct) =>
        {
            var user = await svc.GetByIdAsync(id, ct);
            return user is null ? Results.NotFound() : Results.Ok(user);
        });

        group.MapPost("/", async (CreateUserRequest req, IUserService svc, CancellationToken ct) =>
        {
            var result = await svc.CreateAsync(req, ct);
            return result.IsSuccess
                ? Results.Created($"/api/users/{result.Value!.Id}", result.Value)
                : Results.BadRequest(result.Error);
        });
    }
}
```

---

## Record Types

```csharp
// ALWAYS records for DTOs (immutable)
public record UserDto(int Id, string Email, string FullName);

// With validation
public record CreateUserRequest
{
    public string Email { get; init; } = string.Empty;
    public string FullName { get; init; } = string.Empty;

    public ValidationResult Validate() => /* ... */;
}

// Classes for entities (mutable — EF needs this)
public class User
{
    public int Id { get; set; }
    public string Email { get; set; } = string.Empty;
    public ICollection<Order> Orders { get; set; } = new List<Order>();
}
```

---

## LINQ Patterns

```csharp
// Method syntax over query syntax (more readable in chains)
var result = users
    .Where(u => u.IsActive && u.Role == Role.Admin)
    .OrderBy(u => u.FullName)
    .Select(u => new { u.Id, u.Email })
    .ToListAsync(ct);

// Pagination
var items = await query
    .OrderBy(u => u.FullName)
    .Skip((page - 1) * pageSize)
    .Take(pageSize)
    .ToListAsync(ct);
```

---

## Testing

```csharp
public class UserServiceTests
{
    private readonly Mock<IUserRepository> _repoMock = new();
    private readonly UserService _sut = new(_repoMock.Object);

    [Fact]
    public async Task GetByIdAsync_WhenUserExists_ReturnsUser()
    {
        // Arrange
        var userId = 1;
        var user = new User { Id = userId, Email = "test@test.com" };
        _repoMock.Setup(r => r.GetByIdAsync(userId, It.IsAny<CancellationToken>()))
            .ReturnsAsync(user);

        // Act
        var result = await _sut.GetByIdAsync(userId);

        // Assert
        Assert.NotNull(result);
        Assert.Equal("test@test.com", result!.Email);
    }
}
```

**Naming:** `[Method]_[Scenario]_[ExpectedResult]`

---

## Project Structure Options

### Clean Architecture (complex/domain-driven)

```
src/
├── Domain/Entities/, ValueObjects/, Interfaces/
├── Application/UseCases/, DTOs/, Interfaces/, Services/
├── Infrastructure/Data/, Repositories/, Services/
└── API/Controllers/, Middleware/, Filters/
```

### Layered (simpler projects)

```
src/
├── ProjectName.Core/      # Business logic, entities
├── ProjectName.Infrastructure/ # Data access
└── ProjectName.API/       # Controllers, middleware
```

---

## Code Style

- **Namespaces:** Singular (`ProjectName.Domain.Entities`)
- **Properties over fields:** Always
- **Braces:** Consistent with project (team decision)
- **Structured logging:**

```csharp
_logger.LogInformation(
    "Creating order {OrderId} for user {UserId}",
    orderId, userId);
```

---

## Performance

```csharp
// NO: N queries
foreach (var id in ids)
    var user = context.Users.Find(id);

// YES: 1 query
var users = await context.Users
    .Where(u => ids.Contains(u.Id))
    .ToListAsync();
```

Versions

RepositoryScoreLicence
This page · CamiloAndresGTRUniandes/lucy-ai100MIT
ericrisco/rsc-harness100MIT
nimadorostkar/Claude-Skills-collection100MIT
lynricsy/hyperskills100MIT

Database snapshot: 13.11.2026 · package version 9815dda82b5c (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 90dotnet-patterns
    Use when writing C#/.NET backend code — ASP.NET Core APIs (minimal APIs or MVC), workers, EF Core data access. Builder playbook: layout, DI lifetimes, async/cancellation, EF Core discipline, options pattern, error contract, testing shape. Complements csharp-reviewer.
  • 100csharp-developer
    Use this agent when building ASP.NET Core web APIs, cloud-native .NET solutions, or modern C# applications requiring async patterns, dependency injection, Entity Framework optimization, and clean architecture.
  • 100dotnet-patterns
    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.
  • 100dotnet-patterns
    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.
  • 100dotnet-core-expert
    Use when building .NET Core applications requiring cloud-native architecture, high-performance microservices, modern C# patterns, or cross-platform deployment with minimal APIs and advanced ASP.NET Core features.
  • 100dotnet-idioms
    .NET 8+ framework architecture: Minimal APIs, EF Core data access, IOptions configuration, middleware pipelines, and WebApplicationFactory testing. Use when building ASP.NET Core services, Web APIs, or .NET cloud backends. Pair with csharp-idioms.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.