diff --git a/.claude/skills/aspire-integration-testing/SKILL.md b/.claude/skills/aspire-integration-testing/SKILL.md
new file mode 100644
index 00000000..ca7ac929
--- /dev/null
+++ b/.claude/skills/aspire-integration-testing/SKILL.md
@@ -0,0 +1,217 @@
+---
+name: aspire-integration-testing
+description: Write integration tests using .NET Aspire's testing facilities with xUnit. Covers test fixtures, distributed application setup, endpoint discovery, and patterns for testing ASP.NET Core apps with real dependencies.
+invocable: false
+---
+
+# Integration Testing with .NET Aspire + xUnit
+
+## When to Use This Skill
+
+Use this skill when:
+- Writing integration tests for .NET Aspire applications
+- Testing ASP.NET Core apps with real database connections
+- Verifying service-to-service communication in distributed applications
+- Testing with actual infrastructure (SQL Server, Redis, message queues) in containers
+- Combining Playwright UI tests with Aspire-orchestrated services
+- Testing microservices with proper service discovery and networking
+
+## Reference Files
+
+- [advanced-patterns.md](advanced-patterns.md): Endpoint discovery, database testing, Playwright, conditional config, Respawn, service communication, message queues
+- [ci-and-tooling.md](ci-and-tooling.md): CI/CD integration, custom resource waiters, Aspire CLI with MCP
+
+## Core Principles
+
+1. **Real Dependencies** - Use actual infrastructure (databases, caches) via Aspire, not mocks
+2. **Dynamic Port Binding** - Let Aspire assign ports dynamically (`127.0.0.1:0`) to avoid conflicts
+3. **Fixture Lifecycle** - Use `IAsyncLifetime` for proper test fixture setup and teardown
+4. **Endpoint Discovery** - Never hard-code URLs; discover endpoints from Aspire at runtime
+5. **Parallel Isolation** - Use xUnit collections to control test parallelization
+6. **Health Checks** - Always wait for services to be healthy before running tests
+
+## High-Level Testing Architecture
+
+```
+┌─────────────────┐ ┌──────────────────────┐
+│ xUnit test file │──uses────────────►│ AspireFixture │
+└─────────────────┘ │ (IAsyncLifetime) │
+ └──────────────────────┘
+ │
+ │ starts
+ ▼
+ ┌───────────────────────────┐
+ │ DistributedApplication │
+ │ (from AppHost) │
+ └───────────────────────────┘
+ │ exposes
+ ▼
+ ┌──────────────────────────────┐
+ │ Dynamic HTTP Endpoints │
+ └──────────────────────────────┘
+ │ consumed by
+ ▼
+ ┌─────────────────────────┐
+ │ HttpClient / Playwright│
+ └─────────────────────────┘
+```
+
+## Required NuGet Packages
+
+```xml
+
+
+
+
+
+
+```
+
+## CRITICAL: File Watcher Fix for Integration Tests
+
+When running many integration tests that each start an IHost, the default .NET host builder enables file watchers for configuration reload. This exhausts file descriptor limits on Linux.
+
+**Add this to your test project before any tests run:**
+
+```csharp
+// TestEnvironmentInitializer.cs
+using System.Runtime.CompilerServices;
+
+namespace YourApp.Tests;
+
+internal static class TestEnvironmentInitializer
+{
+ [ModuleInitializer]
+ internal static void Initialize()
+ {
+ // Disable config file watching in test hosts
+ // Prevents file descriptor exhaustion (inotify watch limit) on Linux
+ Environment.SetEnvironmentVariable("DOTNET_HOSTBUILDER__RELOADCONFIGONCHANGE", "false");
+ }
+}
+```
+
+## Pattern 1: Basic Aspire Test Fixture (Modern API)
+
+```csharp
+using Aspire.Hosting;
+using Aspire.Hosting.Testing;
+
+public sealed class AspireAppFixture : IAsyncLifetime
+{
+ private DistributedApplication? _app;
+
+ public DistributedApplication App => _app
+ ?? throw new InvalidOperationException("App not initialized");
+
+ public async Task InitializeAsync()
+ {
+ var builder = await DistributedApplicationTestingBuilder
+ .CreateAsync([
+ "YourApp:UseVolumes=false",
+ "YourApp:Environment=IntegrationTest",
+ "YourApp:Replicas=1"
+ ]);
+
+ _app = await builder.BuildAsync();
+
+ using var startupCts = new CancellationTokenSource(TimeSpan.FromMinutes(10));
+ await _app.StartAsync(startupCts.Token);
+
+ using var healthCts = new CancellationTokenSource(TimeSpan.FromMinutes(5));
+ await _app.ResourceNotifications.WaitForResourceHealthyAsync("api", healthCts.Token);
+ }
+
+ public Uri GetEndpoint(string resourceName, string scheme = "https")
+ {
+ return _app?.GetEndpoint(resourceName, scheme)
+ ?? throw new InvalidOperationException($"Endpoint for '{resourceName}' not found");
+ }
+
+ public async Task DisposeAsync()
+ {
+ if (_app is not null)
+ {
+ await _app.DisposeAsync();
+ }
+ }
+}
+```
+
+## Pattern 2: Using the Fixture in Tests
+
+```csharp
+[CollectionDefinition("Aspire collection")]
+public class AspireCollection : ICollectionFixture { }
+
+[Collection("Aspire collection")]
+public class IntegrationTests
+{
+ private readonly AspireAppFixture _fixture;
+
+ public IntegrationTests(AspireAppFixture fixture)
+ {
+ _fixture = fixture;
+ }
+
+ [Fact]
+ public async Task Application_ShouldStart()
+ {
+ var httpClient = _fixture.App.CreateHttpClient("yourapp");
+ var response = await httpClient.GetAsync("/");
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ }
+}
+```
+
+See [advanced-patterns.md](advanced-patterns.md) for Endpoint Discovery, Database Testing, Playwright UI Tests, Conditional Resource Configuration, Respawn database reset, Service-to-Service Communication, and Message Queue testing patterns.
+
+## Common Patterns Summary
+
+| Pattern | Use Case |
+|---------|----------|
+| Basic Fixture | Simple HTTP endpoint testing |
+| Endpoint Discovery | Avoid hard-coded URLs |
+| Database Testing | Verify data access layer |
+| Playwright Integration | Full UI testing with real backend |
+| Configuration Override | Test-specific settings |
+| Health Checks | Ensure services are ready |
+| Service Communication | Test distributed system interactions |
+| Message Queue Testing | Verify async messaging |
+
+## Tricky / Non-Obvious Tips
+
+| Problem | Solution |
+|---------|----------|
+| Tests timeout immediately | Call `await _app.StartAsync()` and wait for services to be healthy |
+| Port conflicts between tests | Use xUnit `CollectionDefinition` to share fixtures |
+| Flaky tests due to timing | Implement proper health check polling instead of `Task.Delay()` |
+| Can't connect to SQL Server | Retrieve connection string dynamically via `GetConnectionStringAsync()` |
+| Parallel tests interfere | Use `[Collection]` attribute to run related tests sequentially |
+| Aspire dashboard conflicts | Only one dashboard can run at a time; tests reuse the same instance |
+
+## Best Practices
+
+1. **Use `IAsyncLifetime`** - Ensures proper async initialization and cleanup
+2. **Share fixtures via collections** - Reduces test execution time by reusing app instances
+3. **Discover endpoints dynamically** - Never hard-code localhost:5000 or similar
+4. **Wait for health checks** - Don't assume services are immediately ready
+5. **Test with real dependencies** - Aspire makes it easy to use real SQL, Redis, etc.
+6. **Clean up resources** - Always implement `DisposeAsync` properly
+7. **Use meaningful test data** - Seed databases with realistic test data
+8. **Test failure scenarios** - Verify error handling and resilience
+9. **Keep tests isolated** - Each test should be independent and order-agnostic
+10. **Monitor test execution time** - If tests are slow, consider parallelization
+
+See [ci-and-tooling.md](ci-and-tooling.md) for GitHub Actions setup, custom resource waiters, and Aspire CLI/MCP integration.
+
+---
+
+## Debugging Tips
+
+1. **Run Aspire Dashboard** - When tests fail, check the dashboard at `http://localhost:15888`
+2. **Use Aspire CLI with MCP** - Let AI assistants query real application state
+3. **Enable detailed logging** - Set `ASPIRE_ALLOW_UNSECURED_TRANSPORT=true` for more verbose output
+4. **Check container logs** - Use `docker logs` to inspect container output
+5. **Use breakpoints in fixtures** - Debug fixture initialization to catch startup issues
+6. **Verify resource names** - Ensure resource names match between AppHost and tests
diff --git a/.claude/skills/aspire-integration-testing/advanced-patterns.md b/.claude/skills/aspire-integration-testing/advanced-patterns.md
new file mode 100644
index 00000000..c1120a20
--- /dev/null
+++ b/.claude/skills/aspire-integration-testing/advanced-patterns.md
@@ -0,0 +1,439 @@
+# Advanced Testing Patterns
+
+Extended patterns for Aspire integration testing including endpoint discovery, database testing, Playwright, conditional configuration, Respawn, and service communication.
+
+## Contents
+
+- [Endpoint Discovery](#endpoint-discovery)
+- [Testing with Database Dependencies](#testing-with-database-dependencies)
+- [Combining with Playwright for UI Tests](#combining-with-playwright-for-ui-tests)
+- [Conditional Resource Configuration for Tests](#conditional-resource-configuration-for-tests)
+- [Database Reset with Respawn](#database-reset-with-respawn)
+- [Waiting for Resource Readiness](#waiting-for-resource-readiness)
+- [Testing Service-to-Service Communication](#testing-service-to-service-communication)
+- [Testing with Message Queues](#testing-with-message-queues)
+
+## Endpoint Discovery
+
+```csharp
+public static class DistributedApplicationExtensions
+{
+ public static ResourceEndpoint GetEndpoint(
+ this DistributedApplication app,
+ string resourceName,
+ string? endpointName = null)
+ {
+ var resource = app.GetResource(resourceName);
+
+ if (resource is null)
+ throw new InvalidOperationException(
+ $"Resource '{resourceName}' not found");
+
+ var endpoint = endpointName is null
+ ? resource.GetEndpoints().FirstOrDefault()
+ : resource.GetEndpoint(endpointName);
+
+ if (endpoint is null)
+ throw new InvalidOperationException(
+ $"Endpoint '{endpointName}' not found on resource '{resourceName}'");
+
+ return endpoint;
+ }
+
+ public static string GetEndpointUrl(
+ this DistributedApplication app,
+ string resourceName,
+ string? endpointName = null)
+ {
+ var endpoint = app.GetEndpoint(resourceName, endpointName);
+ return endpoint.Url;
+ }
+}
+
+// Usage in tests
+[Fact]
+public async Task CanAccessWebApplication()
+{
+ var url = _fixture.App.GetEndpointUrl("yourapp");
+ var client = new HttpClient { BaseAddress = new Uri(url) };
+
+ var response = await client.GetAsync("/health");
+
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+}
+```
+
+## Testing with Database Dependencies
+
+```csharp
+public class DatabaseIntegrationTests
+{
+ private readonly AspireAppFixture _fixture;
+
+ public DatabaseIntegrationTests(AspireAppFixture fixture)
+ {
+ _fixture = fixture;
+ }
+
+ [Fact]
+ public async Task Database_ShouldBeInitialized()
+ {
+ // Get connection string from Aspire
+ var dbResource = _fixture.App.GetResource("yourdb");
+ var connectionString = await dbResource
+ .GetConnectionStringAsync();
+
+ // Test database access
+ await using var connection = new SqlConnection(connectionString);
+ await connection.OpenAsync();
+
+ var result = await connection.QuerySingleAsync(
+ "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES");
+
+ Assert.True(result > 0, "Database should have tables");
+ }
+}
+```
+
+## Combining with Playwright for UI Tests
+
+```csharp
+using Microsoft.Playwright;
+
+public sealed class AspirePlaywrightFixture : IAsyncLifetime
+{
+ private DistributedApplication? _app;
+ private IPlaywright? _playwright;
+ private IBrowser? _browser;
+
+ public DistributedApplication App => _app!;
+ public IBrowser Browser => _browser!;
+
+ public async Task InitializeAsync()
+ {
+ // Start Aspire application
+ var appHost = await DistributedApplicationTestingBuilder
+ .CreateAsync();
+
+ _app = await appHost.BuildAsync();
+ await _app.StartAsync();
+
+ // Wait for app to be fully ready
+ await Task.Delay(2000); // Or use proper health check polling
+
+ // Start Playwright
+ _playwright = await Playwright.CreateAsync();
+ _browser = await _playwright.Chromium.LaunchAsync(new()
+ {
+ Headless = true
+ });
+ }
+
+ public async Task DisposeAsync()
+ {
+ if (_browser is not null)
+ await _browser.DisposeAsync();
+
+ _playwright?.Dispose();
+
+ if (_app is not null)
+ await _app.DisposeAsync();
+ }
+}
+
+[Collection("Aspire Playwright collection")]
+public class UIIntegrationTests
+{
+ private readonly AspirePlaywrightFixture _fixture;
+
+ public UIIntegrationTests(AspirePlaywrightFixture fixture)
+ {
+ _fixture = fixture;
+ }
+
+ [Fact]
+ public async Task HomePage_ShouldLoad()
+ {
+ var url = _fixture.App.GetEndpointUrl("yourapp");
+ var page = await _fixture.Browser.NewPageAsync();
+
+ await page.GotoAsync(url);
+
+ var title = await page.TitleAsync();
+ Assert.NotEmpty(title);
+ }
+}
+```
+
+## Conditional Resource Configuration for Tests
+
+Design your AppHost to support different configurations for interactive development (F5/CLI) vs automated test fixtures.
+
+> **Default to production-like behavior in AppHost.** Tests explicitly override what they need to be different.
+
+### Configuration Class in AppHost
+
+```csharp
+public class AppHostConfiguration
+{
+ public bool UseVolumes { get; set; } = true;
+ public string ExecutionMode { get; set; } = "Clustered";
+ public bool EnableTestAuth { get; set; } = false;
+ public bool UseFakeExternalServices { get; set; } = false;
+ public int Replicas { get; set; } = 1;
+}
+```
+
+### AppHost Conditional Logic
+
+```csharp
+var builder = DistributedApplication.CreateBuilder(args);
+
+var config = builder.Configuration.GetSection("App")
+ .Get() ?? new AppHostConfiguration();
+
+var postgres = builder.AddPostgres("postgres").WithPgAdmin();
+if (config.UseVolumes)
+{
+ postgres.WithDataVolume();
+}
+var db = postgres.AddDatabase("appdb");
+
+var migrations = builder.AddProject("migrations")
+ .WaitFor(db)
+ .WithReference(db);
+
+var api = builder.AddProject("api")
+ .WaitForCompletion(migrations)
+ .WithReference(db)
+ .WithEnvironment("AkkaSettings__ExecutionMode", config.ExecutionMode)
+ .WithEnvironment("Testing__EnableTestAuth", config.EnableTestAuth.ToString())
+ .WithEnvironment("ExternalServices__UseFakes", config.UseFakeExternalServices.ToString());
+
+if (config.Replicas > 1)
+{
+ api.WithReplicas(config.Replicas);
+}
+
+builder.Build().Run();
+```
+
+### Test Fixture Overrides
+
+```csharp
+var builder = await DistributedApplicationTestingBuilder
+ .CreateAsync([
+ "App:UseVolumes=false",
+ "App:ExecutionMode=LocalTest",
+ "App:EnableTestAuth=true",
+ "App:UseFakeExternalServices=true"
+ ]);
+```
+
+### Common Conditional Settings
+
+| Setting | F5/Development | Test Fixture | Purpose |
+|---------|----------------|--------------|---------|
+| `UseVolumes` | `true` (persist data) | `false` (clean slate) | Database isolation |
+| `ExecutionMode` | `Clustered` (realistic) | `LocalTest` or `Clustered` | Actor system mode |
+| `EnableTestAuth` | `false` (use real OAuth) | `true` (/dev-login) | Bypass OAuth in tests |
+| `UseFakeServices` | `false` (real integrations) | `true` (no external calls) | External API isolation |
+| `Replicas` | `1` or more | `1` (simplicity) | Scale configuration |
+
+### Test Authentication Pattern
+
+```csharp
+// In API startup, conditionally add test auth
+if (builder.Configuration.GetValue("Testing:EnableTestAuth"))
+{
+ app.MapPost("/dev-login", async (DevLoginRequest request, IAuthService auth) =>
+ {
+ var token = await auth.GenerateTokenAsync(request.UserId, request.Roles);
+ return Results.Ok(new { token });
+ });
+}
+
+// In tests
+public async Task LoginAsTestUser(string userId, string[] roles)
+{
+ var response = await _httpClient.PostAsJsonAsync("/dev-login",
+ new { UserId = userId, Roles = roles });
+ var result = await response.Content.ReadFromJsonAsync();
+ return result!.Token;
+}
+```
+
+### Fake External Services Pattern
+
+```csharp
+public static IServiceCollection AddExternalServices(
+ this IServiceCollection services,
+ IConfiguration config)
+{
+ if (config.GetValue("ExternalServices:UseFakes"))
+ {
+ services.AddSingleton();
+ services.AddSingleton();
+ services.AddSingleton();
+ }
+ else
+ {
+ services.AddSingleton();
+ services.AddSingleton();
+ services.AddSingleton();
+ }
+
+ return services;
+}
+```
+
+## Database Reset with Respawn
+
+For tests that modify data, use [Respawn](https://github.com/jbogard/Respawn) to reset between tests:
+
+```csharp
+using Respawn;
+
+public class AspireFixtureWithReset : IAsyncLifetime
+{
+ private DistributedApplication? _app;
+ private Respawner? _respawner;
+ private string? _connectionString;
+
+ public async Task InitializeAsync()
+ {
+ var builder = await DistributedApplicationTestingBuilder
+ .CreateAsync([
+ "YourApp:UseVolumes=false"
+ ]);
+
+ _app = await builder.BuildAsync();
+ await _app.StartAsync();
+
+ await _app.ResourceNotifications.WaitForResourceHealthyAsync("api");
+
+ var dbResource = _app.GetResource("appdb");
+ _connectionString = await dbResource.GetConnectionStringAsync();
+
+ _respawner = await Respawner.CreateAsync(_connectionString, new RespawnerOptions
+ {
+ TablesToIgnore = new[]
+ {
+ "__EFMigrationsHistory",
+ "schema_version",
+ "AspNetRoles"
+ },
+ DbAdapter = DbAdapter.Postgres
+ });
+ }
+
+ public async Task ResetDatabaseAsync()
+ {
+ if (_respawner is not null && _connectionString is not null)
+ {
+ await _respawner.ResetAsync(_connectionString);
+ }
+ }
+
+ public async Task DisposeAsync()
+ {
+ if (_app is not null)
+ await _app.DisposeAsync();
+ }
+}
+```
+
+## Waiting for Resource Readiness
+
+```csharp
+public static class ResourceExtensions
+{
+ public static async Task WaitForHealthyAsync(
+ this DistributedApplication app,
+ string resourceName,
+ TimeSpan? timeout = null)
+ {
+ timeout ??= TimeSpan.FromSeconds(30);
+ var cts = new CancellationTokenSource(timeout.Value);
+
+ var resource = app.GetResource(resourceName);
+
+ while (!cts.Token.IsCancellationRequested)
+ {
+ try
+ {
+ var httpClient = app.CreateHttpClient(resourceName);
+ var response = await httpClient.GetAsync(
+ "/health",
+ cts.Token);
+
+ if (response.IsSuccessStatusCode)
+ return;
+ }
+ catch
+ {
+ // Resource not ready yet
+ }
+
+ await Task.Delay(500, cts.Token);
+ }
+
+ throw new TimeoutException(
+ $"Resource '{resourceName}' did not become healthy within {timeout}");
+ }
+}
+```
+
+## Testing Service-to-Service Communication
+
+```csharp
+[Fact]
+public async Task WebApp_ShouldCallApi()
+{
+ var webClient = _fixture.App.CreateHttpClient("webapp");
+ var apiClient = _fixture.App.CreateHttpClient("api");
+
+ // Verify API is accessible
+ var apiResponse = await apiClient.GetAsync("/api/data");
+ Assert.True(apiResponse.IsSuccessStatusCode);
+
+ // Verify WebApp calls API correctly
+ var webResponse = await webClient.GetAsync("/fetch-data");
+ Assert.True(webResponse.IsSuccessStatusCode);
+
+ var content = await webResponse.Content.ReadAsStringAsync();
+ Assert.NotEmpty(content);
+}
+```
+
+## Testing with Message Queues
+
+```csharp
+[Fact]
+public async Task MessageQueue_ShouldProcessMessages()
+{
+ var rabbitMqResource = _fixture.App.GetResource("messaging");
+ var connectionString = await rabbitMqResource
+ .GetConnectionStringAsync();
+
+ var factory = new ConnectionFactory
+ {
+ Uri = new Uri(connectionString)
+ };
+
+ using var connection = await factory.CreateConnectionAsync();
+ using var channel = await connection.CreateChannelAsync();
+
+ await channel.QueueDeclareAsync("test-queue", durable: false);
+ await channel.BasicPublishAsync(
+ exchange: "",
+ routingKey: "test-queue",
+ body: Encoding.UTF8.GetBytes("test message"));
+
+ // Wait for processing
+ await Task.Delay(1000);
+
+ // Verify message was processed
+ // (check database, file system, or other side effects)
+}
+```
diff --git a/.claude/skills/aspire-integration-testing/ci-and-tooling.md b/.claude/skills/aspire-integration-testing/ci-and-tooling.md
new file mode 100644
index 00000000..8cd3cb26
--- /dev/null
+++ b/.claude/skills/aspire-integration-testing/ci-and-tooling.md
@@ -0,0 +1,195 @@
+# CI/CD and Tooling
+
+CI/CD integration, advanced resource waiters, and Aspire CLI with MCP for AI-assisted development.
+
+## Contents
+
+- [CI/CD Integration](#cicd-integration)
+- [Advanced Custom Resource Waiters](#advanced-custom-resource-waiters)
+- [Aspire CLI and MCP Integration](#aspire-cli-and-mcp-integration)
+
+## CI/CD Integration
+
+### GitHub Actions Example
+
+```yaml
+name: Integration Tests
+
+on:
+ push:
+ branches: [ main, dev ]
+ pull_request:
+ branches: [ main, dev ]
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v3
+
+ - name: Setup .NET
+ uses: actions/setup-dotnet@v3
+ with:
+ dotnet-version: 9.0.x
+
+ - name: Restore dependencies
+ run: dotnet restore
+
+ - name: Build
+ run: dotnet build --no-restore -c Release
+
+ - name: Run integration tests
+ run: |
+ dotnet test tests/YourApp.IntegrationTests \
+ --no-build \
+ -c Release \
+ --logger trx \
+ --collect:"XPlat Code Coverage"
+
+ - name: Publish test results
+ uses: actions/upload-artifact@v3
+ if: always()
+ with:
+ name: test-results
+ path: "**/TestResults/*.trx"
+```
+
+## Advanced Custom Resource Waiters
+
+```csharp
+public static class ResourceWaiters
+{
+ public static async Task WaitForSqlServerAsync(
+ this DistributedApplication app,
+ string resourceName,
+ CancellationToken ct = default)
+ {
+ var resource = app.GetResource(resourceName);
+ var connectionString = await resource.GetConnectionStringAsync(ct);
+
+ var retryCount = 0;
+ const int maxRetries = 30;
+
+ while (retryCount < maxRetries)
+ {
+ try
+ {
+ await using var connection = new SqlConnection(connectionString);
+ await connection.OpenAsync(ct);
+ return; // Success!
+ }
+ catch (SqlException)
+ {
+ retryCount++;
+ await Task.Delay(1000, ct);
+ }
+ }
+
+ throw new TimeoutException(
+ $"SQL Server resource '{resourceName}' did not become ready");
+ }
+
+ public static async Task WaitForRedisAsync(
+ this DistributedApplication app,
+ string resourceName,
+ CancellationToken ct = default)
+ {
+ var resource = app.GetResource(resourceName);
+ var connectionString = await resource.GetConnectionStringAsync(ct);
+
+ var retryCount = 0;
+ const int maxRetries = 30;
+
+ while (retryCount < maxRetries)
+ {
+ try
+ {
+ var redis = await ConnectionMultiplexer.ConnectAsync(
+ connectionString);
+ await redis.GetDatabase().PingAsync();
+ return; // Success!
+ }
+ catch
+ {
+ retryCount++;
+ await Task.Delay(1000, ct);
+ }
+ }
+
+ throw new TimeoutException(
+ $"Redis resource '{resourceName}' did not become ready");
+ }
+}
+
+// Usage
+public async Task InitializeAsync()
+{
+ _app = await appHost.BuildAsync();
+ await _app.StartAsync();
+
+ // Wait for dependencies to be ready
+ await _app.WaitForSqlServerAsync("yourdb");
+ await _app.WaitForRedisAsync("cache");
+}
+```
+
+## Aspire CLI and MCP Integration
+
+Aspire 13.1+ includes MCP (Model Context Protocol) integration for AI coding assistants like Claude Code. This allows AI tools to query application state, view logs, and inspect traces.
+
+### Installing the Aspire CLI
+
+```bash
+# Install the Aspire CLI globally
+dotnet tool install -g aspire.cli
+
+# Or update existing installation
+dotnet tool update -g aspire.cli
+```
+
+### Initializing MCP for Claude Code
+
+```bash
+# Navigate to your Aspire project
+cd src/MyApp.AppHost
+
+# Initialize MCP configuration (auto-detects Claude Code)
+aspire mcp init
+```
+
+This creates the necessary configuration files for Claude Code to connect to your running Aspire application.
+
+### Running with MCP Enabled
+
+```bash
+# Run your Aspire app with MCP server
+aspire run
+
+# The CLI will output the MCP endpoint URL
+# Claude Code can then connect and query:
+# - Resource states and health status
+# - Real-time console logs
+# - Distributed traces
+# - Available Aspire integrations
+```
+
+### MCP Capabilities
+
+When connected, AI assistants can:
+- **Query resources** - Get resource states, endpoints, health status
+- **Debug with logs** - Access real-time console output from all services
+- **Investigate telemetry** - View structured logs and distributed traces
+- **Execute commands** - Run resource-specific commands
+- **Discover integrations** - List available Aspire hosting integrations (Redis, PostgreSQL, Azure services)
+
+### Benefits for Development
+
+- AI assistants can see your actual running application state
+- Debugging assistance uses real telemetry data
+- No need for manual log copying/pasting
+- AI can help correlate distributed trace spans
+
+For more details, see:
+- [Aspire MCP Configuration](https://aspire.dev/get-started/configure-mcp/)
+- [Aspire CLI Commands](https://aspire.dev/reference/cli/commands/aspire-mcp-init/)
diff --git a/.claude/skills/csharp-coding-standards/SKILL.md b/.claude/skills/csharp-coding-standards/SKILL.md
new file mode 100644
index 00000000..773d93a0
--- /dev/null
+++ b/.claude/skills/csharp-coding-standards/SKILL.md
@@ -0,0 +1,327 @@
+---
+name: csharp-coding-standards
+description: Write modern, high-performance C# code using records, pattern matching, value objects, async/await, Span/Memory, and best-practice API design patterns. Emphasizes functional-style programming with C# 12+ features.
+invocable: false
+---
+
+# Modern C# Coding Standards
+
+## When to Use This Skill
+
+Use this skill when:
+
+- Writing new C# code or refactoring existing code
+- Designing public APIs for libraries or services
+- Optimizing performance-critical code paths
+- Implementing domain models with strong typing
+- Building async/await-heavy applications
+- Working with binary data, buffers, or high-throughput scenarios
+
+## Reference Files
+
+- [value-objects-and-patterns.md](value-objects-and-patterns.md): Full value object examples and pattern matching code
+- [performance-and-api-design.md](performance-and-api-design.md): Span/Memory examples and API design principles
+- [composition-and-error-handling.md](composition-and-error-handling.md): Composition over inheritance, Result type, testing patterns
+- [anti-patterns-and-reflection.md](anti-patterns-and-reflection.md): Reflection avoidance and common anti-patterns
+
+## Core Principles
+
+1. **Immutability by Default** - Use `record` types and `init`-only properties
+2. **Type Safety** - Leverage nullable reference types and value objects
+3. **Modern Pattern Matching** - Use `switch` expressions and patterns extensively
+4. **Async Everywhere** - Prefer async APIs with proper cancellation support
+5. **Zero-Allocation Patterns** - Use `Span` and `Memory` for performance-critical code
+6. **API Design** - Accept abstractions, return appropriately specific types
+7. **Composition Over Inheritance** - Avoid abstract base classes, prefer composition
+8. **Value Objects as Structs** - Use `readonly record struct` for value objects
+9. **Formatting** - Use `.editorconfig` for consistent code style across the project and enforce with `dotnet format`
+10. **Passing Tests** - Any times significant changes are made, ensure unit tests pass and add new tests for new functionality.
+11. **Service Registration** - If your changes add new services in an app that uses dependency injection, ensure they are registered in the DI container and that any required configuration is added to the appsettings.json file.
+
+---
+
+## Language Patterns
+
+### Records for Immutable Data (C# 9+)
+
+Use `record` types for DTOs, messages, events, and domain entities.
+
+```csharp
+// Simple immutable DTO
+public record CustomerDto(string Id, string Name, string Email);
+
+// Record with validation in constructor
+public record EmailAddress
+{
+ public string Value { get; init; }
+
+ public EmailAddress(string value)
+ {
+ if (string.IsNullOrWhiteSpace(value) || !value.Contains('@'))
+ throw new ArgumentException("Invalid email address", nameof(value));
+
+ Value = value;
+ }
+}
+
+// Records with collections - use IReadOnlyList
+public record ShoppingCart(
+ string CartId,
+ string CustomerId,
+ IReadOnlyList Items
+)
+{
+ public decimal Total => Items.Sum(item => item.Price * item.Quantity);
+}
+```
+
+**When to use `record class` vs `record struct`:**
+
+- `record class` (default): Reference types, use for entities, aggregates, DTOs with multiple properties
+- `record struct`: Value types, use for value objects (see next section)
+
+### Value Objects as readonly record struct
+
+Value objects should **always be `readonly record struct`** for performance and value semantics. Use explicit conversions, never implicit operators.
+
+```csharp
+public readonly record struct OrderId
+{
+ public string Value { get; }
+ public OrderId(string value) => Value = !string.IsNullOrWhiteSpace(value)
+ ? value
+ : throw new ArgumentException("OrderId cannot be empty", nameof(value));
+ public override string ToString() => Value;
+}
+
+public readonly record struct Money(decimal Amount, string Currency);
+public readonly record struct CustomerId(Guid Value)
+{
+ public static CustomerId New() => new(Guid.NewGuid());
+}
+```
+
+See [value-objects-and-patterns.md](value-objects-and-patterns.md) for complete examples including multi-value objects, factory patterns, and the no-implicit-conversion rule.
+
+### Pattern Matching (C# 8-12)
+
+Use switch expressions, property patterns, relational patterns, and list patterns for cleaner code.
+
+```csharp
+public decimal CalculateDiscount(Order order) => order switch
+{
+ { Total: > 1000m } => order.Total * 0.15m,
+ { Total: > 500m } => order.Total * 0.10m,
+ { Total: > 100m } => order.Total * 0.05m,
+ _ => 0m
+};
+```
+
+See [value-objects-and-patterns.md](value-objects-and-patterns.md) for full pattern matching examples.
+
+---
+
+### Nullable Reference Types (C# 8+)
+
+Enable nullable reference types in your project and handle nulls explicitly.
+
+```csharp
+// In .csproj
+
+ enable
+
+
+// Explicit nullability
+public string? FindUserName(string userId)
+{
+ var user = _repository.Find(userId);
+ return user?.Name;
+}
+
+// Pattern matching with null checks
+public decimal GetDiscount(Customer? customer) => customer switch
+{
+ null => 0m,
+ { IsVip: true } => 0.20m,
+ { OrderCount: > 10 } => 0.10m,
+ _ => 0.05m
+};
+
+// Guard clauses with ArgumentNullException.ThrowIfNull (C# 11+)
+public void ProcessOrder(Order? order)
+{
+ ArgumentNullException.ThrowIfNull(order);
+ // order is now non-nullable in this scope
+ Console.WriteLine(order.Id);
+}
+```
+
+---
+
+## Composition Over Inheritance
+
+**Avoid abstract base classes.** Use interfaces + composition. Use static helpers for shared logic. Use records with factory methods for variants.
+
+See [composition-and-error-handling.md](composition-and-error-handling.md) for full examples.
+
+---
+
+## Performance Patterns
+
+### Async/Await Best Practices
+
+```csharp
+// Async all the way - always accept CancellationToken
+public async Task GetOrderAsync(string orderId, CancellationToken cancellationToken)
+{
+ var order = await _repository.GetAsync(orderId, cancellationToken);
+ return order;
+}
+
+// ValueTask for frequently-called, often-synchronous methods
+public ValueTask GetCachedOrderAsync(string orderId, CancellationToken cancellationToken)
+{
+ if (_cache.TryGetValue(orderId, out var order))
+ return ValueTask.FromResult(order);
+ return GetFromDatabaseAsync(orderId, cancellationToken);
+}
+
+// IAsyncEnumerable for streaming
+public async IAsyncEnumerable StreamOrdersAsync(
+ string customerId,
+ [EnumeratorCancellation] CancellationToken cancellationToken = default)
+{
+ await foreach (var order in _repository.StreamAllAsync(cancellationToken))
+ {
+ if (order.CustomerId == customerId)
+ yield return order;
+ }
+}
+```
+
+**Key rules:**
+
+- Always accept `CancellationToken` with `= default`
+- Use `ConfigureAwait(false)` in library code
+- Never block on async code (no `.Result` or `.Wait()`)
+- Use linked CancellationTokenSource for timeouts
+
+### Span and Memory
+
+Use `Span` for synchronous zero-allocation operations, `Memory` for async, and `ArrayPool` for large temporary buffers.
+
+See [performance-and-api-design.md](performance-and-api-design.md) for complete Span/Memory examples and the API design section.
+
+---
+
+## Error Handling: Result Type
+
+For expected errors, use `Result` instead of exceptions. Use exceptions only for unexpected/system errors.
+
+See [composition-and-error-handling.md](composition-and-error-handling.md) for the full Result type implementation and usage examples.
+
+---
+
+## Avoid Reflection-Based Metaprogramming
+
+**Banned:** AutoMapper, Mapster, ExpressMapper. Use explicit mapping extension methods instead. Use `UnsafeAccessorAttribute` (.NET 8+) when you genuinely need private member access.
+
+See [anti-patterns-and-reflection.md](anti-patterns-and-reflection.md) for full guidance.
+
+---
+
+## Code Organization
+
+```csharp
+// File: Domain/Orders/Order.cs
+
+namespace MyApp.Domain.Orders;
+
+// 1. Primary domain type
+public record Order(
+ OrderId Id,
+ CustomerId CustomerId,
+ Money Total,
+ OrderStatus Status,
+ IReadOnlyList Items
+)
+{
+ public bool IsCompleted => Status is OrderStatus.Completed;
+
+ public Result AddItem(OrderItem item)
+ {
+ if (Status is not OrderStatus.Draft)
+ return Result.Failure(
+ new OrderError("ORDER_NOT_DRAFT", "Can only add items to draft orders"));
+
+ var newItems = Items.Append(item).ToList();
+ var newTotal = new Money(
+ Items.Sum(i => i.Total.Amount) + item.Total.Amount,
+ Total.Currency);
+
+ return Result.Success(
+ this with { Items = newItems, Total = newTotal });
+ }
+}
+
+// 2. Enums for state
+public enum OrderStatus { Draft, Submitted, Processing, Completed, Cancelled }
+
+// 3. Related types
+public record OrderItem(ProductId ProductId, Quantity Quantity, Money UnitPrice)
+{
+ public Money Total => new(UnitPrice.Amount * Quantity.Value, UnitPrice.Currency);
+}
+
+// 4. Value objects
+public readonly record struct OrderId(Guid Value)
+{
+ public static OrderId New() => new(Guid.NewGuid());
+}
+
+// 5. Errors
+public readonly record struct OrderError(string Code, string Message);
+```
+
+---
+
+## Best Practices Summary
+
+### DO's
+
+- Use `record` for DTOs, messages, and domain entities
+- Use `readonly record struct` for value objects
+- Leverage pattern matching with `switch` expressions
+- Enable and respect nullable reference types
+- Use async/await for all I/O operations
+- Accept `CancellationToken` in all async methods
+- Use `Span` and `Memory` for high-performance scenarios
+- Accept abstractions (`IEnumerable`, `IReadOnlyList`)
+- Use `Result` for expected errors
+- Pool buffers with `ArrayPool` for large allocations
+- Prefer composition over inheritance
+
+### DON'Ts
+
+- Don't use mutable classes when records work
+- Don't use classes for value objects (use `readonly record struct`)
+- Don't create deep inheritance hierarchies
+- Don't ignore nullable reference type warnings
+- Don't block on async code (`.Result`, `.Wait()`)
+- Don't use `byte[]` when `Span` suffices
+- Don't forget `CancellationToken` parameters
+- Don't return mutable collections from APIs
+- Don't throw exceptions for expected business errors
+- Don't allocate large arrays repeatedly (use `ArrayPool`)
+
+See [anti-patterns-and-reflection.md](anti-patterns-and-reflection.md) for detailed anti-pattern examples.
+
+---
+
+## Additional Resources
+
+- **C# Language Specification**: https://learn.microsoft.com/en-us/dotnet/csharp/
+- **Pattern Matching**: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching
+- **Span and Memory**: https://learn.microsoft.com/en-us/dotnet/standard/memory-and-spans/
+- **Async Best Practices**: https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming
+- **.NET Performance Tips**: https://learn.microsoft.com/en-us/dotnet/framework/performance/
diff --git a/.claude/skills/csharp-coding-standards/anti-patterns-and-reflection.md b/.claude/skills/csharp-coding-standards/anti-patterns-and-reflection.md
new file mode 100644
index 00000000..f5ffc0b4
--- /dev/null
+++ b/.claude/skills/csharp-coding-standards/anti-patterns-and-reflection.md
@@ -0,0 +1,288 @@
+# Anti-Patterns and Reflection Avoidance
+
+Guidelines on avoiding reflection-based metaprogramming and common C# anti-patterns.
+
+## Contents
+
+- [Avoid Reflection-Based Metaprogramming](#avoid-reflection-based-metaprogramming)
+- [UnsafeAccessorAttribute (.NET 8+)](#unsafeaccessorattribute-net-8)
+- [Anti-Patterns to Avoid](#anti-patterns-to-avoid)
+
+## Avoid Reflection-Based Metaprogramming
+
+**Prefer statically-typed, explicit code over reflection-based "magic" libraries.**
+
+Reflection-based libraries like AutoMapper trade compile-time safety for convenience. When mappings break, you find out at runtime (or worse, in production) instead of at compile time.
+
+### Banned Libraries
+
+| Library | Problem |
+|---------|---------|
+| **AutoMapper** | Reflection magic, hidden mappings, runtime failures, hard to debug |
+| **Mapster** | Same issues as AutoMapper |
+| **ExpressMapper** | Same issues |
+
+### Why Reflection Mapping Fails
+
+```csharp
+// With AutoMapper - compiles fine, fails at runtime
+public record UserDto(string Id, string Name, string Email);
+public record UserEntity(Guid Id, string FullName, string EmailAddress);
+
+// This mapping silently produces garbage:
+// - Id: string vs Guid mismatch
+// - Name vs FullName: no match, null/default
+// - Email vs EmailAddress: no match, null/default
+var dto = _mapper.Map(entity); // Compiles! Breaks at runtime.
+```
+
+### Use Explicit Mapping Methods Instead
+
+```csharp
+// Extension method - compile-time checked, easy to find, easy to debug
+public static class UserMappings
+{
+ public static UserDto ToDto(this UserEntity entity) => new(
+ Id: entity.Id.ToString(),
+ Name: entity.FullName,
+ Email: entity.EmailAddress);
+
+ public static UserEntity ToEntity(this CreateUserRequest request) => new(
+ Id: Guid.NewGuid(),
+ FullName: request.Name,
+ EmailAddress: request.Email);
+}
+
+// Usage - explicit and traceable
+var dto = entity.ToDto();
+var entity = request.ToEntity();
+```
+
+### Benefits of Explicit Mappings
+
+| Aspect | AutoMapper | Explicit Methods |
+|--------|------------|------------------|
+| **Compile-time safety** | No - runtime errors | Yes - compiler catches mismatches |
+| **Discoverability** | Hidden in profiles | "Go to Definition" works |
+| **Debugging** | Black box | Step through code |
+| **Refactoring** | Rename breaks silently | IDE renames correctly |
+| **Performance** | Reflection overhead | Direct property access |
+| **Testing** | Need integration tests | Simple unit tests |
+
+### Complex Mappings
+
+For complex transformations, explicit code is even more valuable:
+
+```csharp
+public static OrderSummaryDto ToSummary(this Order order) => new(
+ OrderId: order.Id.Value.ToString(),
+ CustomerName: order.Customer.FullName,
+ ItemCount: order.Items.Count,
+ Total: order.Items.Sum(i => i.Quantity * i.UnitPrice),
+ Status: order.Status switch
+ {
+ OrderStatus.Pending => "Awaiting Payment",
+ OrderStatus.Paid => "Processing",
+ OrderStatus.Shipped => "On the Way",
+ OrderStatus.Delivered => "Completed",
+ _ => "Unknown"
+ },
+ FormattedDate: order.CreatedAt.ToString("MMMM d, yyyy"));
+```
+
+This is:
+- **Readable**: Anyone can understand the transformation
+- **Debuggable**: Set a breakpoint, inspect values
+- **Testable**: Pass an Order, assert on the result
+- **Refactorable**: Change a property name, compiler tells you everywhere it's used
+
+### When Reflection is Acceptable
+
+Reflection has legitimate uses, but mapping DTOs isn't one of them:
+
+| Use Case | Acceptable? |
+|----------|-------------|
+| Serialization (System.Text.Json, Newtonsoft) | Yes - well-tested, source generators available |
+| Dependency injection container | Yes - framework infrastructure |
+| ORM entity mapping (EF Core) | Yes - necessary for database abstraction |
+| Test fixtures and builders | Sometimes - for convenience in tests only |
+| **DTO/domain object mapping** | **No - use explicit methods** |
+
+## UnsafeAccessorAttribute (.NET 8+)
+
+When you genuinely need to access private or internal members (serializers, test helpers, framework code), use `UnsafeAccessorAttribute` instead of traditional reflection. It provides **zero-overhead, AOT-compatible** member access.
+
+```csharp
+// AVOID: Traditional reflection - slow, allocates, breaks AOT
+var field = typeof(Order).GetField("_status", BindingFlags.NonPublic | BindingFlags.Instance);
+var status = (OrderStatus)field!.GetValue(order)!;
+
+// PREFER: UnsafeAccessor - zero overhead, AOT-compatible
+[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_status")]
+static extern ref OrderStatus GetStatusField(Order order);
+
+var status = GetStatusField(order); // Direct access, no reflection
+```
+
+**Supported accessor kinds:**
+
+```csharp
+// Private field access
+[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_items")]
+static extern ref List GetItemsField(Order order);
+
+// Private method access
+[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "Recalculate")]
+static extern void CallRecalculate(Order order);
+
+// Private static field
+[UnsafeAccessor(UnsafeAccessorKind.StaticField, Name = "_instanceCount")]
+static extern ref int GetInstanceCount(Order order);
+
+// Private constructor
+[UnsafeAccessor(UnsafeAccessorKind.Constructor)]
+static extern Order CreateOrder(OrderId id, CustomerId customerId);
+```
+
+**Why UnsafeAccessor over reflection:**
+
+| Aspect | Reflection | UnsafeAccessor |
+|--------|------------|----------------|
+| Performance | Slow (100-1000x) | Zero overhead |
+| AOT compatible | No | Yes |
+| Allocations | Yes (boxing, arrays) | None |
+| Compile-time checked | No | Partially (signature) |
+
+**Use cases:**
+- Serializers accessing private backing fields
+- Test helpers verifying internal state
+- Framework code that needs to bypass visibility
+
+**Resources:**
+- [A new way of doing reflection with .NET 8](https://steven-giesel.com/blogPost/05ecdd16-8dc4-490f-b1cf-780c994346a4)
+- [Accessing private members without reflection in .NET 8.0](https://www.strathweb.com/2023/10/accessing-private-members-without-reflection-in-net-8-0/)
+- [Modern .NET Reflection with UnsafeAccessor](https://blog.ndepend.com/modern-net-reflection-with-unsafeaccessor/)
+
+## Anti-Patterns to Avoid
+
+### Don't: Use mutable DTOs
+
+```csharp
+// BAD: Mutable DTO
+public class CustomerDto
+{
+ public string Id { get; set; }
+ public string Name { get; set; }
+}
+
+// GOOD: Immutable record
+public record CustomerDto(string Id, string Name);
+```
+
+### Don't: Use classes for value objects
+
+```csharp
+// BAD: Value object as class
+public class OrderId
+{
+ public string Value { get; }
+ public OrderId(string value) => Value = value;
+}
+
+// GOOD: Value object as readonly record struct
+public readonly record struct OrderId(string Value);
+```
+
+### Don't: Create deep inheritance hierarchies
+
+```csharp
+// BAD: Deep inheritance
+public abstract class Entity { }
+public abstract class AggregateRoot : Entity { }
+public abstract class Order : AggregateRoot { }
+public class CustomerOrder : Order { }
+
+// GOOD: Flat structure with composition
+public interface IEntity
+{
+ Guid Id { get; }
+}
+
+public record Order(OrderId Id, CustomerId CustomerId, Money Total) : IEntity
+{
+ Guid IEntity.Id => Id.Value;
+}
+```
+
+### Don't: Return List when you mean IReadOnlyList
+
+```csharp
+// BAD: Exposes internal list for modification
+public List GetOrders() => _orders;
+
+// GOOD: Returns read-only view
+public IReadOnlyList GetOrders() => _orders;
+```
+
+### Don't: Use byte[] when ReadOnlySpan works
+
+```csharp
+// BAD: Allocates array on every call
+public byte[] GetHeader()
+{
+ var header = new byte[64];
+ // Fill header
+ return header;
+}
+
+// GOOD: Zero allocation with Span
+public void GetHeader(Span destination)
+{
+ if (destination.Length < 64)
+ throw new ArgumentException("Buffer too small");
+
+ // Fill header directly into caller's buffer
+}
+```
+
+### Don't: Forget CancellationToken in async methods
+
+```csharp
+// BAD: No cancellation support
+public async Task GetOrderAsync(OrderId id)
+{
+ return await _repository.GetAsync(id);
+}
+
+// GOOD: Cancellation support
+public async Task GetOrderAsync(
+ OrderId id,
+ CancellationToken cancellationToken = default)
+{
+ return await _repository.GetAsync(id, cancellationToken);
+}
+```
+
+### Don't: Block on async code
+
+```csharp
+// BAD: Deadlock risk!
+public Order GetOrder(OrderId id)
+{
+ return GetOrderAsync(id).Result;
+}
+
+// BAD: Also deadlock risk!
+public Order GetOrder(OrderId id)
+{
+ return GetOrderAsync(id).GetAwaiter().GetResult();
+}
+
+// GOOD: Async all the way
+public async Task GetOrderAsync(
+ OrderId id,
+ CancellationToken cancellationToken)
+{
+ return await _repository.GetAsync(id, cancellationToken);
+}
+```
diff --git a/.claude/skills/csharp-coding-standards/composition-and-error-handling.md b/.claude/skills/csharp-coding-standards/composition-and-error-handling.md
new file mode 100644
index 00000000..8a133243
--- /dev/null
+++ b/.claude/skills/csharp-coding-standards/composition-and-error-handling.md
@@ -0,0 +1,273 @@
+# Composition and Error Handling
+
+Composition over inheritance, Result type pattern, and testing patterns for modern C#.
+
+## Contents
+
+- [Composition Over Inheritance](#composition-over-inheritance)
+- [Result Type Pattern](#result-type-pattern)
+- [Testing Patterns](#testing-patterns)
+
+## Composition Over Inheritance
+
+**Avoid abstract base classes and inheritance hierarchies.** Use composition and interfaces instead.
+
+```csharp
+// BAD: Abstract base class hierarchy
+public abstract class PaymentProcessor
+{
+ public abstract Task ProcessAsync(Money amount);
+
+ protected async Task ValidateAsync(Money amount)
+ {
+ // Shared validation logic
+ return amount.Amount > 0;
+ }
+}
+
+public class CreditCardProcessor : PaymentProcessor
+{
+ public override async Task ProcessAsync(Money amount)
+ {
+ await ValidateAsync(amount);
+ // Process credit card...
+ }
+}
+
+// GOOD: Composition with interfaces
+public interface IPaymentProcessor
+{
+ Task ProcessAsync(Money amount, CancellationToken cancellationToken);
+}
+
+public interface IPaymentValidator
+{
+ Task ValidateAsync(Money amount, CancellationToken cancellationToken);
+}
+
+// Concrete implementations compose validators
+public sealed class CreditCardProcessor : IPaymentProcessor
+{
+ private readonly IPaymentValidator _validator;
+ private readonly ICreditCardGateway _gateway;
+
+ public CreditCardProcessor(IPaymentValidator validator, ICreditCardGateway gateway)
+ {
+ _validator = validator;
+ _gateway = gateway;
+ }
+
+ public async Task ProcessAsync(Money amount, CancellationToken cancellationToken)
+ {
+ var validation = await _validator.ValidateAsync(amount, cancellationToken);
+ if (!validation.IsValid)
+ return PaymentResult.Failed(validation.Error);
+
+ return await _gateway.ChargeAsync(amount, cancellationToken);
+ }
+}
+
+// GOOD: Static helper classes for shared logic (no inheritance)
+public static class PaymentValidation
+{
+ public static ValidationResult ValidateAmount(Money amount)
+ {
+ if (amount.Amount <= 0)
+ return ValidationResult.Invalid("Amount must be positive");
+
+ if (amount.Amount > 10000m)
+ return ValidationResult.Invalid("Amount exceeds maximum");
+
+ return ValidationResult.Valid();
+ }
+}
+
+// GOOD: Records for modeling variants (not inheritance)
+public enum PaymentType { CreditCard, BankTransfer, Cash }
+
+public record PaymentMethod
+{
+ public PaymentType Type { get; init; }
+ public string? Last4 { get; init; } // For credit cards
+ public string? AccountNumber { get; init; } // For bank transfers
+
+ public static PaymentMethod CreditCard(string last4) => new()
+ {
+ Type = PaymentType.CreditCard,
+ Last4 = last4
+ };
+
+ public static PaymentMethod BankTransfer(string accountNumber) => new()
+ {
+ Type = PaymentType.BankTransfer,
+ AccountNumber = accountNumber
+ };
+
+ public static PaymentMethod Cash() => new() { Type = PaymentType.Cash };
+}
+```
+
+**When inheritance is acceptable:**
+- Framework requirements (e.g., `ControllerBase` in ASP.NET Core)
+- Library integration (e.g., custom exceptions inheriting from `Exception`)
+- **These should be rare cases in your application code**
+
+## Result Type Pattern
+
+For expected errors, use a **domain-specific result type** instead of exceptions. Don't build a generic `Result` — each operation knows what success and failure look like, so let the result type reflect that. Use sealed records with factory methods and enum error codes.
+
+```csharp
+// Enum for error classification - type-safe and switchable
+public enum OrderErrorCode
+{
+ ValidationError,
+ InsufficientInventory,
+ NotFound
+}
+
+// Domain-specific result type - sealed record with factory methods
+public sealed record CreateOrderResult
+{
+ public bool IsSuccess { get; private init; }
+ public Order? Order { get; private init; }
+ public OrderErrorCode? ErrorCode { get; private init; }
+ public string? ErrorMessage { get; private init; }
+
+ public static CreateOrderResult Success(Order order) => new()
+ {
+ IsSuccess = true,
+ Order = order
+ };
+
+ public static CreateOrderResult Failed(OrderErrorCode code, string message) => new()
+ {
+ IsSuccess = false,
+ ErrorCode = code,
+ ErrorMessage = message
+ };
+}
+
+// Usage example
+public sealed class OrderService(IOrderRepository repository)
+{
+ public async Task CreateOrderAsync(
+ CreateOrderRequest request,
+ CancellationToken cancellationToken)
+ {
+ if (!IsValid(request))
+ return CreateOrderResult.Failed(
+ OrderErrorCode.ValidationError, "Invalid order request");
+
+ if (!await HasInventoryAsync(request.Items, cancellationToken))
+ return CreateOrderResult.Failed(
+ OrderErrorCode.InsufficientInventory, "Items out of stock");
+
+ var order = new Order(
+ OrderId.New(),
+ new CustomerId(request.CustomerId),
+ request.Items);
+
+ await repository.SaveAsync(order, cancellationToken);
+
+ return CreateOrderResult.Success(order);
+ }
+
+ // Map result to HTTP response - switch on enum error codes
+ public IActionResult MapToActionResult(CreateOrderResult result)
+ {
+ if (result.IsSuccess)
+ return new OkObjectResult(result.Order);
+
+ return result.ErrorCode switch
+ {
+ OrderErrorCode.ValidationError =>
+ new BadRequestObjectResult(new { error = result.ErrorMessage }),
+ OrderErrorCode.InsufficientInventory =>
+ new ConflictObjectResult(new { error = result.ErrorMessage }),
+ OrderErrorCode.NotFound =>
+ new NotFoundObjectResult(new { error = result.ErrorMessage }),
+ _ => new ObjectResult(new { error = result.ErrorMessage }) { StatusCode = 500 }
+ };
+ }
+}
+```
+
+**When to use Result vs Exceptions:**
+- **Use Result**: Expected errors (validation, business rules, not found)
+- **Use Exceptions**: Unexpected errors (network failures, system errors, programming bugs)
+
+## Testing Patterns
+
+```csharp
+// Use record for test data builders
+public record OrderBuilder
+{
+ public OrderId Id { get; init; } = OrderId.New();
+ public CustomerId CustomerId { get; init; } = CustomerId.New();
+ public Money Total { get; init; } = new Money(100m, "USD");
+ public IReadOnlyList Items { get; init; } = Array.Empty();
+
+ public Order Build() => new(Id, CustomerId, Total, Items);
+}
+
+// Use 'with' expression for test variations
+[Fact]
+public void CalculateDiscount_LargeOrder_AppliesCorrectDiscount()
+{
+ // Arrange
+ var baseOrder = new OrderBuilder().Build();
+ var largeOrder = baseOrder with
+ {
+ Total = new Money(1500m, "USD")
+ };
+
+ // Act
+ var discount = _service.CalculateDiscount(largeOrder);
+
+ // Assert
+ discount.Should().Be(new Money(225m, "USD")); // 15% of 1500
+}
+
+// Span-based testing
+[Theory]
+[InlineData("ORD-12345", true)]
+[InlineData("INVALID", false)]
+public void TryParseOrderId_VariousInputs_ReturnsExpectedResult(
+ string input,
+ bool expected)
+{
+ // Act
+ var result = OrderIdParser.TryParse(input.AsSpan(), out var orderId);
+
+ // Assert
+ result.Should().Be(expected);
+}
+
+// Testing with value objects
+[Fact]
+public void Money_Add_SameCurrency_ReturnsSum()
+{
+ // Arrange
+ var money1 = new Money(100m, "USD");
+ var money2 = new Money(50m, "USD");
+
+ // Act
+ var result = money1.Add(money2);
+
+ // Assert
+ result.Should().Be(new Money(150m, "USD"));
+}
+
+[Fact]
+public void Money_Add_DifferentCurrency_ThrowsException()
+{
+ // Arrange
+ var usd = new Money(100m, "USD");
+ var eur = new Money(50m, "EUR");
+
+ // Act & Assert
+ var act = () => usd.Add(eur);
+ act.Should().Throw()
+ .WithMessage("*different currencies*");
+}
+```
diff --git a/.claude/skills/csharp-coding-standards/performance-and-api-design.md b/.claude/skills/csharp-coding-standards/performance-and-api-design.md
new file mode 100644
index 00000000..daf3a285
--- /dev/null
+++ b/.claude/skills/csharp-coding-standards/performance-and-api-design.md
@@ -0,0 +1,346 @@
+# Performance and API Design Patterns
+
+Zero-allocation patterns with Span/Memory and API design principles for accepting and returning the right types.
+
+## Contents
+
+- [Span and Memory for Zero-Allocation Code](#spant-and-memoryt-for-zero-allocation-code)
+- [API Design Principles](#api-design-principles)
+- [Method Signatures Best Practices](#method-signatures-best-practices)
+
+## Span and Memory for Zero-Allocation Code
+
+Use `Span` and `Memory` instead of `byte[]` or `string` for performance-critical code.
+
+```csharp
+// Span for synchronous, zero-allocation operations
+public int ParseOrderId(ReadOnlySpan input)
+{
+ // Work with data without allocations
+ if (!input.StartsWith("ORD-"))
+ throw new FormatException("Invalid order ID format");
+
+ var numberPart = input.Slice(4);
+ return int.Parse(numberPart);
+}
+
+// stackalloc with Span
+public void FormatMessage()
+{
+ Span buffer = stackalloc char[256];
+ var written = FormatInto(buffer);
+ var message = new string(buffer.Slice(0, written));
+}
+
+// SkipLocalsInit with stackalloc - skips zero-initialization for performance
+// By default, .NET zero-initializes all locals (.locals init flag). This can have
+// measurable overhead with stackalloc. Use [SkipLocalsInit] when:
+// - You write to the buffer before reading (like FormatInto below)
+// - Profiling shows zero-init as a bottleneck
+// WARNING: Reading before writing returns garbage data
+// Requires: true in .csproj
+// See: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/general#skiplocalsinit-attribute
+using System.Runtime.CompilerServices;
+[SkipLocalsInit]
+public void FormatMessage()
+{
+ Span buffer = stackalloc char[256];
+ var written = FormatInto(buffer);
+ var message = new string(buffer.Slice(0, written));
+}
+
+// Memory for async operations (Span can't cross await)
+public async Task ReadDataAsync(
+ Memory buffer,
+ CancellationToken cancellationToken)
+{
+ return await _stream.ReadAsync(buffer, cancellationToken);
+}
+
+// String manipulation with Span to avoid allocations
+public bool TryParseKeyValue(ReadOnlySpan line, out string key, out string value)
+{
+ key = string.Empty;
+ value = string.Empty;
+
+ int colonIndex = line.IndexOf(':');
+ if (colonIndex == -1)
+ return false;
+
+ // Only allocate strings once we know the format is valid
+ key = new string(line.Slice(0, colonIndex).Trim());
+ value = new string(line.Slice(colonIndex + 1).Trim());
+ return true;
+}
+
+// ArrayPool for temporary large buffers
+public async Task ProcessLargeFileAsync(
+ Stream stream,
+ CancellationToken cancellationToken)
+{
+ var buffer = ArrayPool.Shared.Rent(8192);
+ try
+ {
+ int bytesRead;
+ while ((bytesRead = await stream.ReadAsync(buffer.AsMemory(), cancellationToken)) > 0)
+ {
+ ProcessChunk(buffer.AsSpan(0, bytesRead));
+ }
+ }
+ finally
+ {
+ ArrayPool.Shared.Return(buffer);
+ }
+}
+
+// Hybrid buffer pattern for transient UTF-8 work. See caveats of SkipLocalsInit in the corresponding section.
+
+[SkipLocalsInit]
+static short GenerateHashCode(string? key)
+{
+ if (key is null) return 0;
+
+ const int StackLimit = 256;
+
+ var enc = Encoding.UTF8;
+ var max = enc.GetMaxByteCount(key.Length);
+
+ byte[]? rented = null;
+ Span buf = max <= StackLimit
+ ? stackalloc byte[StackLimit]
+ : (rented = ArrayPool.Shared.Rent(max));
+
+ try
+ {
+ var written = enc.GetBytes(key.AsSpan(), buf);
+ ComputeHash(buf[..written], out var h1, out var h2);
+ return unchecked((short)(h1 ^ h2));
+ }
+ finally
+ {
+ if (rented is not null) ArrayPool.Shared.Return(rented);
+ }
+}
+
+// Span-based parsing without substring allocations
+public static (string Protocol, string Host, int Port) ParseUrl(ReadOnlySpan url)
+{
+ var protocolEnd = url.IndexOf("://");
+ var protocol = new string(url.Slice(0, protocolEnd));
+
+ var afterProtocol = url.Slice(protocolEnd + 3);
+ var portStart = afterProtocol.IndexOf(':');
+
+ var host = new string(afterProtocol.Slice(0, portStart));
+ var portSpan = afterProtocol.Slice(portStart + 1);
+ var port = int.Parse(portSpan);
+
+ return (protocol, host, port);
+}
+
+// Writing data to Span
+public bool TryFormatOrderId(int orderId, Span destination, out int charsWritten)
+{
+ const string prefix = "ORD-";
+
+ if (destination.Length < prefix.Length + 10)
+ {
+ charsWritten = 0;
+ return false;
+ }
+
+ prefix.AsSpan().CopyTo(destination);
+ var numberWritten = orderId.TryFormat(
+ destination.Slice(prefix.Length),
+ out var numberChars);
+
+ charsWritten = prefix.Length + numberChars;
+ return numberWritten;
+}
+```
+
+**When to use what:**
+
+| Type | Use Case |
+|------|----------|
+| `Span` | Synchronous operations, stack-allocated buffers, slicing without allocation |
+| `ReadOnlySpan` | Read-only views, method parameters for data you won't modify |
+| `Memory` | Async operations (Span can't cross await boundaries) |
+| `ReadOnlyMemory` | Read-only async operations |
+| `byte[]` | When you need to store data long-term or pass to APIs requiring arrays |
+| `ArrayPool` | Large temporary buffers (>1KB) to avoid GC pressure |
+
+## API Design Principles
+
+### Accept Abstractions, Return Appropriately Specific
+
+**For Parameters (Accept):**
+
+```csharp
+// Accept IEnumerable if you only iterate once
+public decimal CalculateTotal(IEnumerable items)
+{
+ return items.Sum(item => item.Price * item.Quantity);
+}
+
+// Accept IReadOnlyCollection if you need Count
+public bool HasMinimumItems(IReadOnlyCollection items, int minimum)
+{
+ return items.Count >= minimum;
+}
+
+// Accept IReadOnlyList if you need indexing
+public OrderItem GetMiddleItem(IReadOnlyList items)
+{
+ if (items.Count == 0)
+ throw new ArgumentException("List cannot be empty");
+
+ return items[items.Count / 2]; // Indexed access
+}
+
+// Accept ReadOnlySpan for high-performance, zero-allocation APIs
+public int Sum(ReadOnlySpan numbers)
+{
+ int total = 0;
+ foreach (var num in numbers)
+ total += num;
+ return total;
+}
+
+// Accept IAsyncEnumerable for async streaming
+public async Task CountItemsAsync(
+ IAsyncEnumerable orders,
+ CancellationToken cancellationToken)
+{
+ int count = 0;
+ await foreach (var order in orders.WithCancellation(cancellationToken))
+ count++;
+ return count;
+}
+```
+
+**For Return Types:**
+
+```csharp
+// Return IEnumerable for lazy/deferred execution
+public IEnumerable GetOrdersLazy(string customerId)
+{
+ foreach (var order in _repository.Query())
+ {
+ if (order.CustomerId == customerId)
+ yield return order; // Lazy evaluation
+ }
+}
+
+// Return IReadOnlyList for materialized, immutable collections
+public IReadOnlyList GetOrders(string customerId)
+{
+ return _repository
+ .Query()
+ .Where(o => o.CustomerId == customerId)
+ .ToList(); // Materialized
+}
+
+// Return concrete types when callers need mutation
+public List GetMutableOrders(string customerId)
+{
+ // Explicitly allow mutation by returning List
+ return _repository
+ .Query()
+ .Where(o => o.CustomerId == customerId)
+ .ToList();
+}
+
+// Return IAsyncEnumerable for async streaming
+public async IAsyncEnumerable StreamOrdersAsync(
+ string customerId,
+ [EnumeratorCancellation] CancellationToken cancellationToken = default)
+{
+ await foreach (var order in _repository.StreamAllAsync(cancellationToken))
+ {
+ if (order.CustomerId == customerId)
+ yield return order;
+ }
+}
+
+// Return arrays for interop or when caller expects array
+public byte[] SerializeOrder(Order order)
+{
+ // Binary serialization - byte[] is appropriate here
+ return MessagePackSerializer.Serialize(order);
+}
+```
+
+**Summary Table:**
+
+| Scenario | Accept | Return |
+|----------|--------|--------|
+| Only iterate once | `IEnumerable` | `IEnumerable` (if lazy) |
+| Need count | `IReadOnlyCollection` | `IReadOnlyCollection` |
+| Need indexing | `IReadOnlyList` | `IReadOnlyList` |
+| High-performance, sync | `ReadOnlySpan` | `Span` (rarely) |
+| Async streaming | `IAsyncEnumerable` | `IAsyncEnumerable` |
+| Caller needs mutation | - | `List`, `T[]` |
+
+## Method Signatures Best Practices
+
+```csharp
+// Complete async method signature
+public async Task> CreateOrderAsync(
+ CreateOrderRequest request,
+ CancellationToken cancellationToken = default)
+{
+ // Implementation
+}
+
+// Optional parameters at the end
+public async Task> GetOrdersAsync(
+ string customerId,
+ DateTime? startDate = null,
+ DateTime? endDate = null,
+ CancellationToken cancellationToken = default)
+{
+ // Implementation
+}
+
+// Use record for multiple related parameters
+public record SearchOrdersRequest(
+ string? CustomerId,
+ DateTime? StartDate,
+ DateTime? EndDate,
+ OrderStatus? Status,
+ int PageSize = 20,
+ int PageNumber = 1
+);
+
+public async Task> SearchOrdersAsync(
+ SearchOrdersRequest request,
+ CancellationToken cancellationToken = default)
+{
+ // Implementation
+}
+
+// Primary constructors (C# 12+) for simple classes
+public sealed class OrderService(IOrderRepository repository, ILogger logger)
+{
+ public async Task GetOrderAsync(OrderId orderId, CancellationToken cancellationToken)
+ {
+ logger.LogInformation("Fetching order {OrderId}", orderId);
+ return await repository.GetAsync(orderId, cancellationToken);
+ }
+}
+
+// Options pattern for complex configuration
+public sealed class EmailServiceOptions
+{
+ public required string SmtpHost { get; init; }
+ public int SmtpPort { get; init; } = 587;
+ public bool UseSsl { get; init; } = true;
+ public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(30);
+}
+
+public sealed class EmailService(IOptions options)
+{
+ private readonly EmailServiceOptions _options = options.Value;
+}
+```
diff --git a/.claude/skills/csharp-coding-standards/value-objects-and-patterns.md b/.claude/skills/csharp-coding-standards/value-objects-and-patterns.md
new file mode 100644
index 00000000..1b63984a
--- /dev/null
+++ b/.claude/skills/csharp-coding-standards/value-objects-and-patterns.md
@@ -0,0 +1,390 @@
+# Value Objects and Pattern Matching
+
+Full code examples for value objects and pattern matching in modern C#.
+
+## Contents
+
+- [Value Objects as readonly record struct](#value-objects-as-readonly-record-struct)
+- [Constraint-Enforcing Value Objects](#constraint-enforcing-value-objects)
+- [No Implicit Conversions](#no-implicit-conversions)
+- [Pattern Matching (C# 8-12)](#pattern-matching-c-8-12)
+
+## Value Objects as readonly record struct
+
+Value objects should **always be `readonly record struct`** for performance and value semantics.
+
+```csharp
+// Single-value object
+public readonly record struct OrderId
+{
+ public string Value { get; }
+
+ public OrderId(string value)
+ {
+ if (string.IsNullOrWhiteSpace(value))
+ throw new ArgumentException("OrderId cannot be empty", nameof(value));
+ Value = value;
+ }
+
+ public override string ToString() => Value;
+
+ // NO implicit conversions - defeats type safety!
+ // Access inner value explicitly: orderId.Value
+}
+
+// Multi-value object
+public readonly record struct Money
+{
+ public decimal Amount { get; }
+ public string Currency { get; }
+
+ public Money(decimal amount, string currency)
+ {
+ if (amount < 0)
+ throw new ArgumentException("Amount cannot be negative", nameof(amount));
+ Amount = amount;
+ Currency = ValidateCurrency(currency);
+ }
+
+ private static string ValidateCurrency(string currency)
+ {
+ if (string.IsNullOrWhiteSpace(currency) || currency.Length != 3)
+ throw new ArgumentException("Currency must be a 3-letter code", nameof(currency));
+ return currency.ToUpperInvariant();
+ }
+
+ public Money Add(Money other)
+ {
+ if (Currency != other.Currency)
+ throw new InvalidOperationException($"Cannot add {Currency} to {other.Currency}");
+
+ return new Money(Amount + other.Amount, Currency);
+ }
+
+ public override string ToString() => $"{Amount:N2} {Currency}";
+}
+
+// Value object with input normalization
+public readonly record struct PhoneNumber
+{
+ public string Value { get; }
+
+ public PhoneNumber(string input)
+ {
+ if (string.IsNullOrWhiteSpace(input))
+ throw new ArgumentException("Phone number cannot be empty", nameof(input));
+
+ // Normalize: remove all non-digits
+ var digits = new string(input.Where(char.IsDigit).ToArray());
+
+ if (digits.Length is < 10 or > 15)
+ throw new ArgumentException("Phone number must be 10-15 digits", nameof(input));
+
+ Value = digits;
+ }
+
+ public override string ToString() => Value;
+}
+
+// Percentage value object with range validation
+public readonly record struct Percentage
+{
+ private readonly decimal _value;
+
+ public decimal Value => _value;
+
+ public Percentage(decimal value)
+ {
+ if (value < 0 || value > 100)
+ throw new ArgumentOutOfRangeException(nameof(value), "Percentage must be between 0 and 100");
+ _value = value;
+ }
+
+ public decimal AsDecimal() => _value / 100m;
+
+ public static Percentage FromDecimal(decimal decimalValue)
+ {
+ if (decimalValue < 0 || decimalValue > 1)
+ throw new ArgumentOutOfRangeException(nameof(decimalValue), "Decimal must be between 0 and 1");
+ return new Percentage(decimalValue * 100);
+ }
+
+ public override string ToString() => $"{_value}%";
+}
+
+// Strongly-typed ID
+public readonly record struct CustomerId(Guid Value)
+{
+ public static CustomerId New() => new(Guid.NewGuid());
+ public override string ToString() => Value.ToString();
+}
+
+// Quantity with units
+public readonly record struct Quantity
+{
+ public int Value { get; }
+ public string Unit { get; }
+
+ public Quantity(int value, string unit)
+ {
+ if (value < 0)
+ throw new ArgumentException("Quantity cannot be negative", nameof(value));
+ if (string.IsNullOrWhiteSpace(unit))
+ throw new ArgumentException("Unit cannot be empty", nameof(unit));
+ Value = value;
+ Unit = unit;
+ }
+
+ public override string ToString() => $"{Value} {Unit}";
+}
+```
+
+**Why `readonly record struct` for value objects:**
+- **Value semantics**: Equality based on content, not reference
+- **Stack allocation**: Better performance, no GC pressure
+- **Immutability**: `readonly` prevents accidental mutation
+- **Pattern matching**: Works seamlessly with switch expressions
+
+## Constraint-Enforcing Value Objects
+
+Value objects aren't just for identifiers. They're equally valuable for **enforcing domain constraints** on strings, numbers, and URIs — making illegal states unrepresentable at the type level.
+
+**Key principle: validate at construction, trust everywhere else.** Once you have an `AbsoluteUrl`, every consumer knows it's valid without re-checking.
+
+```csharp
+// AbsoluteUrl - enforces HTTP/HTTPS scheme constraints
+public readonly record struct AbsoluteUrl
+{
+ public Uri Value { get; }
+
+ public AbsoluteUrl(string uriString) : this(new Uri(uriString, UriKind.Absolute)) { }
+
+ public AbsoluteUrl(Uri value)
+ {
+ if (!value.IsAbsoluteUri)
+ throw new ArgumentException(
+ $"Value must be an absolute URL. Instead found [{value}]", nameof(value));
+ if (value.Scheme != Uri.UriSchemeHttp && value.Scheme != Uri.UriSchemeHttps)
+ throw new ArgumentException(
+ $"Value must be an HTTP or HTTPS URL. Instead found [{value.Scheme}]", nameof(value));
+ Value = value;
+ }
+
+ ///
+ /// Resolves a potentially relative URL against a base URL.
+ /// Handles Linux quirk where Uri.TryCreate("/path", UriKind.Absolute)
+ /// succeeds as file:///path.
+ ///
+ public static AbsoluteUrl FromRelative(string? url, AbsoluteUrl baseUrl)
+ {
+ if (string.IsNullOrEmpty(url))
+ throw new ArgumentException("URL cannot be null or empty", nameof(url));
+
+ if (Uri.TryCreate(url, UriKind.Absolute, out var absoluteUri) &&
+ (absoluteUri.Scheme == Uri.UriSchemeHttp || absoluteUri.Scheme == Uri.UriSchemeHttps))
+ return new AbsoluteUrl(absoluteUri);
+
+ return new AbsoluteUrl(new Uri(baseUrl.Value, url));
+ }
+
+ public override string ToString() => Value.ToString();
+}
+
+// NonEmptyString - prevents empty/whitespace strings from propagating
+public readonly record struct NonEmptyString
+{
+ public string Value { get; }
+
+ public NonEmptyString(string value)
+ {
+ if (string.IsNullOrWhiteSpace(value))
+ throw new ArgumentException("Value cannot be null or whitespace", nameof(value));
+ Value = value;
+ }
+
+ public override string ToString() => Value;
+}
+
+// EmailAddress - format validation at construction
+public readonly record struct EmailAddress
+{
+ public string Value { get; }
+
+ public EmailAddress(string value)
+ {
+ if (string.IsNullOrWhiteSpace(value))
+ throw new ArgumentException("Email cannot be empty", nameof(value));
+ if (!value.Contains('@') || !value.Contains('.'))
+ throw new ArgumentException($"Invalid email format: {value}", nameof(value));
+ Value = value.ToLowerInvariant();
+ }
+
+ public override string ToString() => Value;
+}
+
+// PositiveAmount - numeric range constraint
+public readonly record struct PositiveAmount
+{
+ public decimal Value { get; }
+
+ public PositiveAmount(decimal value)
+ {
+ if (value <= 0)
+ throw new ArgumentOutOfRangeException(nameof(value), "Amount must be positive");
+ Value = value;
+ }
+
+ public override string ToString() => Value.ToString("N2");
+}
+```
+
+**Why this matters:**
+- APIs like Slack Block Kit silently reject relative URLs with cryptic errors. Transactional email links break if they're relative. `AbsoluteUrl` makes the compiler prevent this.
+- Platform gotchas belong in the value object — e.g., Linux `Uri.TryCreate` treating `/path` as `file:///path` is handled once in `FromRelative`, not at every call site.
+
+### TypeConverter Support for Configuration Binding
+
+Add a `TypeConverter` so your value objects work with `IOptions` and configuration binding:
+
+```csharp
+[TypeConverter(typeof(AbsoluteUrlTypeConverter))]
+public readonly record struct AbsoluteUrl
+{
+ // ... same as above
+}
+
+public sealed class AbsoluteUrlTypeConverter : TypeConverter
+{
+ public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType)
+ => sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
+
+ public override object? ConvertFrom(
+ ITypeDescriptorContext? context, CultureInfo? culture, object value)
+ => value is string s ? new AbsoluteUrl(s) : base.ConvertFrom(context, culture, value);
+}
+
+// Now this works with appsettings.json binding:
+public sealed class WebhookOptions
+{
+ public AbsoluteUrl CallbackUrl { get; set; }
+ public AbsoluteUrl HealthCheckUrl { get; set; }
+}
+
+// appsettings.json:
+// { "Webhook": { "CallbackUrl": "https://example.com/callback" } }
+services.Configure(configuration.GetSection("Webhook"));
+```
+
+## No Implicit Conversions
+
+**CRITICAL: NO implicit conversions.** Implicit operators defeat the purpose of value objects by allowing silent type coercion:
+
+```csharp
+// WRONG - defeats compile-time safety:
+public readonly record struct UserId(Guid Value)
+{
+ public static implicit operator UserId(Guid value) => new(value); // NO!
+ public static implicit operator Guid(UserId value) => value.Value; // NO!
+}
+
+// With implicit operators, this compiles silently:
+void ProcessUser(UserId userId) { }
+ProcessUser(Guid.NewGuid()); // Oops - meant to pass PostId
+
+// CORRECT - all conversions explicit:
+public readonly record struct UserId(Guid Value)
+{
+ public static UserId New() => new(Guid.NewGuid());
+ // No implicit operators
+ // Create: new UserId(guid) or UserId.New()
+ // Extract: userId.Value
+}
+```
+
+Explicit conversions force every boundary crossing to be visible:
+
+```csharp
+// API boundary - explicit conversion IN
+var userId = new UserId(request.UserId); // Validates on entry
+
+// Database boundary - explicit conversion OUT
+await _db.ExecuteAsync(sql, new { UserId = userId.Value });
+```
+
+## Pattern Matching (C# 8-12)
+
+Leverage modern pattern matching for cleaner, more expressive code.
+
+```csharp
+// Switch expressions with value objects
+public string GetPaymentMethodDescription(PaymentMethod payment) => payment switch
+{
+ { Type: PaymentType.CreditCard, Last4: var last4 } => $"Credit card ending in {last4}",
+ { Type: PaymentType.BankTransfer, AccountNumber: var account } => $"Bank transfer from {account}",
+ { Type: PaymentType.Cash } => "Cash payment",
+ _ => "Unknown payment method"
+};
+
+// Property patterns
+public decimal CalculateDiscount(Order order) => order switch
+{
+ { Total: > 1000m } => order.Total * 0.15m,
+ { Total: > 500m } => order.Total * 0.10m,
+ { Total: > 100m } => order.Total * 0.05m,
+ _ => 0m
+};
+
+// Relational and logical patterns
+public string ClassifyTemperature(int temp) => temp switch
+{
+ < 0 => "Freezing",
+ >= 0 and < 10 => "Cold",
+ >= 10 and < 20 => "Cool",
+ >= 20 and < 30 => "Warm",
+ >= 30 => "Hot",
+ _ => throw new ArgumentOutOfRangeException(nameof(temp))
+};
+
+// List patterns (C# 11+)
+public bool IsValidSequence(int[] numbers) => numbers switch
+{
+ [] => false, // Empty
+ [_] => true, // Single element
+ [var first, .., var last] when first < last => true, // First < last
+ _ => false
+};
+
+// Type patterns with null checks
+public string FormatValue(object? value) => value switch
+{
+ null => "null",
+ string s => $"\"{s}\"",
+ int i => i.ToString(),
+ double d => d.ToString("F2"),
+ DateTime dt => dt.ToString("yyyy-MM-dd"),
+ Money m => m.ToString(),
+ IEnumerable