Son aktivite 1 month ago

Scaffold scripts and guide for creating .NET projects, including clean architecture boilerplate and shell/PowerShell helpers.

Vernon Wee Hong KOH bu gisti düzenledi 1 month ago. Düzenlemeye git

1 file changed, 72 insertions, 10 deletions

system-engine-hooks-validation.md

@@ -12,7 +12,7 @@ A `UserPromptSubmit` command hook can:
12 12 - write plain text to stdout, which Claude Code can add as context;
13 13 - return structured JSON to add `additionalContext`, set a session title, or block the prompt.
14 14
15 - The following example injects additional context on every submitted prompt:
15 + The following example injects architecture-adaptive execution guidance on every submitted prompt:
16 16
17 17 ```json
18 18 {
@@ -23,7 +23,7 @@ The following example injects additional context on every submitted prompt:
23 23 "hooks": [
24 24 {
25 25 "type": "command",
26 - "command": "printf '%s\\n' '{\"hookSpecificOutput\":{\"hookEventName\":\"UserPromptSubmit\",\"additionalContext\":\"CRITICAL ARCHITECTURAL CONSTRAINT ACTIVE\\n\\nImplement systems chronologically, layer by layer: Domain -> Infrastructure -> Application -> API. For the active layer, present the plan first, then ask for explicit permission before writing code.\"}}'"
26 + "command": "printf '%s\\n' '{\"hookSpecificOutput\":{\"hookEventName\":\"UserPromptSubmit\",\"additionalContext\":\"ARCHITECTURE-ADAPTIVE EXECUTION GATE ACTIVE\\n\\nWhen implementing or modifying a software project with a recognizable architecture, first identify the architecture, then choose the correct layer, slice, module, or adapter sequence for that architecture. Do not implement the full solution in one pass. For each step, present the plan and intended code layout first, then ask for explicit user approval before writing implementation code.\"}}'"
27 27 }
28 28 ]
29 29 }
@@ -60,7 +60,7 @@ Example Codex hook:
60 60 "hooks": [
61 61 {
62 62 "type": "command",
63 - "command": "printf '%s\\n' 'CRITICAL ARCHITECTURAL CONSTRAINT ACTIVE\\n\\nImplement systems chronologically, layer by layer: Domain -> Infrastructure -> Application -> API. For the active layer, present the plan first, then ask for explicit permission before writing code.'"
63 + "command": "printf '%s\\n' 'ARCHITECTURE-ADAPTIVE EXECUTION GATE ACTIVE\\n\\nWhen implementing or modifying a software project with a recognizable architecture, first identify the architecture, then choose the correct layer, slice, module, or adapter sequence for that architecture. Do not implement the full solution in one pass. For each step, present the plan and intended code layout first, then ask for explicit user approval before writing implementation code.'"
64 64 }
65 65 ]
66 66 }
@@ -88,14 +88,77 @@ Use the appropriate instruction file for the tool:
88 88 Corrected instruction-file wording:
89 89
90 90 ```markdown
91 - # Architectural Execution Guidance
91 + # Architecture-Adaptive Layered Execution Guidance
92 92
93 - When implementing a C# system in this repository:
93 + Apply this guidance when implementing or modifying a software project with a recognizable architecture, including but not limited to:
94 94
95 - 1. Prefer chronological layer order: Domain -> Infrastructure -> Application -> API.
96 - 2. Do not implement multiple architectural layers in one large pass unless the user explicitly asks for that.
97 - 3. Before writing code for a layer, present the intended code layout and ask: "Do I have permission to implement the [Layer Name] layer now?"
98 - 4. Wait for explicit approval before generating implementation code for that layer.
95 + - .NET Clean Architecture / DDD / CQRS
96 + - Spring Boot multilayer architecture
97 + - Vertical Slice Architecture
98 + - Hexagonal / Ports and Adapters Architecture
99 + - Onion Architecture
100 + - Modular monoliths or similarly layered systems
101 +
102 + ## Core Rule
103 +
104 + Do not implement the full solution in one pass.
105 +
106 + First identify the project's architecture and determine the correct implementation sequence for that architecture. Then work layer by layer, slice by slice, module by module, or adapter by adapter as appropriate.
107 +
108 + Before writing implementation code for each step:
109 +
110 + 1. State the detected architecture.
111 + 2. State the active layer, slice, module, or adapter being planned.
112 + 3. Present the intended file/code layout for that step.
113 + 4. Ask: "Do I have permission to implement this step now?"
114 + 5. Wait for explicit user approval before writing code.
115 +
116 + ## Architecture-Specific Sequencing Examples
117 +
118 + For .NET Clean Architecture, DDD, or CQRS, prefer:
119 +
120 + 1. Domain
121 + 2. Application
122 + 3. Infrastructure
123 + 4. API / Presentation
124 +
125 + For Spring Boot multilayer architecture, prefer:
126 +
127 + 1. Domain / Entity / Model
128 + 2. Repository / Persistence
129 + 3. Service / Application Logic
130 + 4. Controller / API
131 + 5. Configuration / Integration
132 +
133 + For Vertical Slice Architecture, prefer:
134 +
135 + 1. One feature slice at a time
136 + 2. Request / Command / Query contract
137 + 3. Handler / Use case logic
138 + 4. Validation
139 + 5. Persistence or integration required by that slice
140 + 6. Endpoint / API exposure
141 + 7. Tests for that slice
142 +
143 + For Hexagonal / Ports and Adapters Architecture, prefer:
144 +
145 + 1. Domain model
146 + 2. Inbound ports / use cases
147 + 3. Outbound ports
148 + 4. Application services
149 + 5. Driven adapters, such as persistence or external APIs
150 + 6. Driving adapters, such as REST controllers, CLI, messaging, or UI
151 + 7. Composition / dependency wiring
152 +
153 + ## Approval Gate
154 +
155 + At every step, stop after the plan and ask for approval.
156 +
157 + Do not generate implementation code until the user explicitly approves the current step.
158 +
159 + ## Scope Limits
160 +
161 + Do not apply this process to trivial edits, documentation-only changes, formatting-only changes, dependency bumps, or isolated bug fixes unless the user asks for architectural sequencing.
99 162 ```
100 163
101 164 Important limits:
@@ -107,4 +170,3 @@ Important limits:
107 170 ## Bottom Line
108 171
109 172 The original Claude Code section was directionally valid but imprecise. The combined "Codex / Cursor / Copilot Prompt Hook" section was incorrect because it mixed real lifecycle hooks with persistent instruction files.
110 -

Vernon Wee Hong KOH bu gisti düzenledi 1 month ago. Düzenlemeye git

1 file changed, 95 insertions, 24 deletions

system-engine-hooks-validation.md

@@ -1,39 +1,110 @@
1 - # Validation: System Engine Hooks
1 + # System Engine Hooks, Rules, and Instruction Files
2 2
3 - The original note is partly correct, but materially misleading.
3 + Different AI coding tools expose different customization mechanisms. Some are real lifecycle hooks that execute commands at fixed points in the runtime. Others are persistent instruction files that are added to the model context as guidance. These should not be described as the same mechanism.
4 4
5 - ## What is correct
5 + ## A. Claude Code CLI Hook (`.claude/settings.json`)
6 6
7 - - Claude Code supports `.claude/settings.json` hooks, including `UserPromptSubmit`, which fires after a user submits a prompt and before Claude processes it.
8 - - Claude Code command hook stdout can add context, and structured JSON output can block or add context.
9 - - GitHub Copilot supports `.github/copilot-instructions.md` as repository custom instructions.
10 - - Cursor supports persistent rules/instructions, but current official docs center on `.cursor/rules/*.mdc`, User Rules, Team Rules, and `AGENTS.md`, not `.cursorrules`.
7 + Claude Code supports lifecycle hooks in `.claude/settings.json`, including `UserPromptSubmit`. This event runs after the user submits a prompt and before Claude processes it.
11 8
12 - ## What is incorrect or overstated
9 + A `UserPromptSubmit` command hook can:
13 10
14 - - `.cursorrules` and `.github/copilot-instructions.md` are not hooks. They are instruction/context files. They do not intercept lifecycle events or execute commands.
15 - - The phrase "Codex / Cursor / Copilot Prompt Hook" is incorrect for Codex. Codex does not use `.cursorrules` or `.github/copilot-instructions.md` as its hook system.
16 - - Codex lifecycle hooks belong in `.codex/hooks.json` or inline `[hooks]` tables in `.codex/config.toml`.
17 - - Codex persistent repo guidance belongs in `AGENTS.md`.
18 - - "Injects directly into the active system context window on every message turn" is too strong. These files may be added as context or instructions, but not necessarily as system-level instructions, and behavior depends on product, mode, trust/settings, and feature support.
19 - - The Claude example may inject text, but it does not guarantee enforcement. It remains subordinate to real system/developer/runtime instructions and product policy.
20 - - "Hardwired into the runtime lifecycle" is defensible for actual lifecycle hook systems like Claude Code hooks and Codex hooks, but not for Cursor or Copilot instruction files.
11 + - read the submitted prompt from JSON on stdin;
12 + - write plain text to stdout, which Claude Code can add as context;
13 + - return structured JSON to add `additionalContext`, set a session title, or block the prompt.
21 14
22 - ## Suggested correction
15 + The following example injects additional context on every submitted prompt:
23 16
24 - Rename section B to:
17 + ```json
18 + {
19 + "hooks": {
20 + "UserPromptSubmit": [
21 + {
22 + "matcher": "",
23 + "hooks": [
24 + {
25 + "type": "command",
26 + "command": "printf '%s\\n' '{\"hookSpecificOutput\":{\"hookEventName\":\"UserPromptSubmit\",\"additionalContext\":\"CRITICAL ARCHITECTURAL CONSTRAINT ACTIVE\\n\\nImplement systems chronologically, layer by layer: Domain -> Infrastructure -> Application -> API. For the active layer, present the plan first, then ask for explicit permission before writing code.\"}}'"
27 + }
28 + ]
29 + }
30 + ]
31 + }
32 + }
33 + ```
25 34
26 - ```markdown
27 - ### B. Persistent Instruction Files, Not Hooks
35 + Important limits:
36 +
37 + - This is a Claude Code hook, not a universal AI-engine hook.
38 + - It can add context or block a prompt, but it does not override higher-priority system, developer, policy, or runtime instructions.
39 + - A bare `echo` hook may add context in Claude Code, but structured JSON with `additionalContext` is more explicit and less ambiguous.
40 +
41 + ## B. Codex Lifecycle Hooks (`.codex/hooks.json` or `.codex/config.toml`)
42 +
43 + Codex has its own lifecycle hook system. Codex does not use `.cursorrules` or `.github/copilot-instructions.md` as hooks.
44 +
45 + Project or user hooks should be configured in one of these Codex-supported locations:
46 +
47 + - `.codex/hooks.json`
48 + - `.codex/config.toml` with inline `[hooks]` tables
49 + - user-level equivalents such as `~/.codex/hooks.json` or `~/.codex/config.toml`
50 +
51 + For durable repository guidance in Codex, use `AGENTS.md`.
52 +
53 + Example Codex hook:
54 +
55 + ```json
56 + {
57 + "hooks": {
58 + "UserPromptSubmit": [
59 + {
60 + "hooks": [
61 + {
62 + "type": "command",
63 + "command": "printf '%s\\n' 'CRITICAL ARCHITECTURAL CONSTRAINT ACTIVE\\n\\nImplement systems chronologically, layer by layer: Domain -> Infrastructure -> Application -> API. For the active layer, present the plan first, then ask for explicit permission before writing code.'"
64 + }
65 + ]
66 + }
67 + ]
68 + }
69 + }
70 + ```
28 71
29 - Cursor and GitHub Copilot can load repository instruction files as persistent guidance, but these files are not executable lifecycle hooks and should not be described as intercepting every message or modifying the system prompt.
72 + Important limits:
30 73
31 - - Cursor: prefer `.cursor/rules/*.mdc` or `AGENTS.md`.
74 + - Codex project-local hooks load only from trusted project `.codex/` configuration.
75 + - Non-managed command hooks may require review and trust before they run.
76 + - Hooks are lifecycle automation, not a guarantee that injected text overrides higher-priority instructions.
77 +
78 + ## C. Cursor and Copilot Instruction Files, Not Hooks
79 +
80 + Cursor and GitHub Copilot support persistent instruction files, but these files are not executable lifecycle hooks and should not be described as intercepting every message or modifying the system prompt.
81 +
82 + Use the appropriate instruction file for the tool:
83 +
84 + - Cursor: prefer `.cursor/rules/*.mdc`, User Rules, Team Rules, or `AGENTS.md`.
32 85 - GitHub Copilot: use `.github/copilot-instructions.md`, `.github/instructions/*.instructions.md`, or `AGENTS.md` where supported.
33 - - Codex: use `AGENTS.md` for durable guidance; use `.codex/hooks.json` or `.codex/config.toml` for lifecycle hooks.
86 + - Codex: use `AGENTS.md` for durable repository guidance; use `.codex/hooks.json` or `.codex/config.toml` for lifecycle hooks.
87 +
88 + Corrected instruction-file wording:
89 +
90 + ```markdown
91 + # Architectural Execution Guidance
92 +
93 + When implementing a C# system in this repository:
94 +
95 + 1. Prefer chronological layer order: Domain -> Infrastructure -> Application -> API.
96 + 2. Do not implement multiple architectural layers in one large pass unless the user explicitly asks for that.
97 + 3. Before writing code for a layer, present the intended code layout and ask: "Do I have permission to implement the [Layer Name] layer now?"
98 + 4. Wait for explicit approval before generating implementation code for that layer.
34 99 ```
35 100
36 - ## Bottom line
101 + Important limits:
102 +
103 + - Instruction files guide model behavior; they are not command hooks.
104 + - They are subject to each product's context loading, settings, trust model, and precedence rules.
105 + - They should be written as repository guidance, not as claims about system-prompt injection.
106 +
107 + ## Bottom Line
37 108
38 - The Claude section is directionally valid but should be more precise. The combined "Codex / Cursor / Copilot Prompt Hook" section is not correct as written.
109 + The original Claude Code section was directionally valid but imprecise. The combined "Codex / Cursor / Copilot Prompt Hook" section was incorrect because it mixed real lifecycle hooks with persistent instruction files.
39 110

Vernon Wee Hong KOH bu gisti düzenledi 1 month ago. Düzenlemeye git

1 file changed, 39 insertions

system-engine-hooks-validation.md(dosya oluşturuldu)

@@ -0,0 +1,39 @@
1 + # Validation: System Engine Hooks
2 +
3 + The original note is partly correct, but materially misleading.
4 +
5 + ## What is correct
6 +
7 + - Claude Code supports `.claude/settings.json` hooks, including `UserPromptSubmit`, which fires after a user submits a prompt and before Claude processes it.
8 + - Claude Code command hook stdout can add context, and structured JSON output can block or add context.
9 + - GitHub Copilot supports `.github/copilot-instructions.md` as repository custom instructions.
10 + - Cursor supports persistent rules/instructions, but current official docs center on `.cursor/rules/*.mdc`, User Rules, Team Rules, and `AGENTS.md`, not `.cursorrules`.
11 +
12 + ## What is incorrect or overstated
13 +
14 + - `.cursorrules` and `.github/copilot-instructions.md` are not hooks. They are instruction/context files. They do not intercept lifecycle events or execute commands.
15 + - The phrase "Codex / Cursor / Copilot Prompt Hook" is incorrect for Codex. Codex does not use `.cursorrules` or `.github/copilot-instructions.md` as its hook system.
16 + - Codex lifecycle hooks belong in `.codex/hooks.json` or inline `[hooks]` tables in `.codex/config.toml`.
17 + - Codex persistent repo guidance belongs in `AGENTS.md`.
18 + - "Injects directly into the active system context window on every message turn" is too strong. These files may be added as context or instructions, but not necessarily as system-level instructions, and behavior depends on product, mode, trust/settings, and feature support.
19 + - The Claude example may inject text, but it does not guarantee enforcement. It remains subordinate to real system/developer/runtime instructions and product policy.
20 + - "Hardwired into the runtime lifecycle" is defensible for actual lifecycle hook systems like Claude Code hooks and Codex hooks, but not for Cursor or Copilot instruction files.
21 +
22 + ## Suggested correction
23 +
24 + Rename section B to:
25 +
26 + ```markdown
27 + ### B. Persistent Instruction Files, Not Hooks
28 +
29 + Cursor and GitHub Copilot can load repository instruction files as persistent guidance, but these files are not executable lifecycle hooks and should not be described as intercepting every message or modifying the system prompt.
30 +
31 + - Cursor: prefer `.cursor/rules/*.mdc` or `AGENTS.md`.
32 + - GitHub Copilot: use `.github/copilot-instructions.md`, `.github/instructions/*.instructions.md`, or `AGENTS.md` where supported.
33 + - Codex: use `AGENTS.md` for durable guidance; use `.codex/hooks.json` or `.codex/config.toml` for lifecycle hooks.
34 + ```
35 +
36 + ## Bottom line
37 +
38 + The Claude section is directionally valid but should be more precise. The combined "Codex / Cursor / Copilot Prompt Hook" section is not correct as written.
39 +

weehong bu gisti düzenledi 1 month ago. Düzenlemeye git

1 file changed, 1 insertion, 2 deletions

dotnet-10-clean-architecture-boilerplate-guide.md

@@ -1363,5 +1363,4 @@ public sealed class ProcessOutboxMessagesJob(
1363 1363 - You need at-least-once delivery guarantees
1364 1364 - You're in a microservices architecture where services communicate via events
1365 1365
1366 - For purely in-process event handling (the common case in a monolith), the existing `DomainEventInterceptor` approach is simpler and sufficient.
1367 - ```
1366 + For purely in-process event handling (the common case in a monolith), the existing `DomainEventInterceptor` approach is simpler and sufficient.

weehong bu gisti düzenledi 1 month ago. Düzenlemeye git

Değişiklik yok

weehong bu gisti düzenledi 1 month ago. Düzenlemeye git

1 file changed, 33 insertions

architecture-validator-rules.md(dosya oluşturuldu)

@@ -0,0 +1,33 @@
1 + # Role: .NET 10 Clean Architecture & CQRS Validator
2 +
3 + You are an expert .NET 10 Software Architect enforcing strict adherence to the project's specific Clean Architecture, Domain-Driven Design (DDD), and CQRS conventions. Your primary task is to review code, flag architectural violations, and suggest compliant refactoring.
4 +
5 + When analyzing or generating code, you MUST adhere to the following rules:
6 +
7 + ## 1. Clean Architecture (CA) Rules
8 + **Goal:** Enforce a strict inward-pointing dependency graph.
9 +
10 + * **Rule CA-1 (The Domain Center):** The `Domain` layer has ZERO NuGet dependencies. It consists of pure C#. Flag any imports from external libraries (e.g., `MediatR`, `EntityFrameworkCore`, `Newtonsoft.Json`) inside the `src/*.Domain` project.
11 + * **Rule CA-2 (Application Layer Isolation):** The `Application` layer handles use cases via `MediatR` and `FluentValidation`. It MUST NOT reference `Microsoft.EntityFrameworkCore` or any I/O-specific libraries. Flag direct database queries or HTTP calls here; they belong in `Infrastructure`.
12 + * **Rule CA-3 (Infrastructure Sealing):** The `Infrastructure` layer implements `IUnitOfWork` and contains the `ApplicationDbContext`. Flag if EF Core entities or interceptors leak into the `Application` or `Domain` layers.
13 +
14 + ## 2. Domain-Driven Design (DDD) Rules
15 + **Goal:** Enforce rich domain models, proper event propagation, and structured failure handling.
16 +
17 + * **Rule DDD-1 (Encapsulation & Auditing):** Entities must inherit from `BaseEntity` or `AuditableEntity`. They MUST NOT have public setters (use `private set` or `private init`). State changes must happen through explicit methods (e.g., `Rename()`, `SetCreatedAt()`).
18 + * **Rule DDD-2 (The Result Pattern):** NEVER throw exceptions for business logic control flow. All domain operations and application handlers MUST return the project's custom `Result` or `Result<T>`. Failures must be defined using the custom `Error` record and its types (`Failure`, `Validation`, `NotFound`, `Conflict`).
19 + * **Rule DDD-3 (Domain Events):** Significant state changes within an entity must call `AddDomainEvent(new MyEvent())`. DO NOT inject publishers into entities. The `DomainEventInterceptor` handles dispatching during `SaveChanges`.
20 +
21 + ## 3. CQRS & MediatR Validation
22 + **Goal:** Strictly separate and validate read and write operations.
23 +
24 + * **Rule CQ-1 (Commands):** Write operations must implement the custom `ICommand` or `ICommand<TResponse>` interfaces. Handlers must implement `ICommandHandler<TCommand>` or `ICommandHandler<TCommand, TResponse>`.
25 + * **Rule CQ-2 (Queries):** Read operations must not mutate state. They should bypass rich domain models for performance if returning complex DTOs. Do not call `AddDomainEvent` or database write operations inside a query handler.
26 + * **Rule CQ-3 (Validation Pipeline):** DO NOT write explicit `if(!isValid)` validation logic inside Command Handlers. Instead, define a `FluentValidation` validator for the Command. The project's `ValidationBehavior` will automatically catch failures and return a `Result.Failure` with an `ErrorType.Validation`.
27 +
28 + ## Output Format for Violations
29 + If you detect a violation, output your response in this exact format:
30 + 1. **[Violation Type]**: (e.g., [CA-1 Domain Dependency Leak] or [DDD-2 Missing Result Pattern])
31 + 2. **File/Line**: Location of the issue.
32 + 3. **Explanation**: Why this violates the .NET 10 boilerplate rules.
33 + 4. **Correction**: Provide the exact refactored C# code snippet to fix it.

weehong bu gisti düzenledi 2 months ago. Düzenlemeye git

Değişiklik yok

weehong bu gisti düzenledi 5 months ago. Düzenlemeye git

1 file changed, 800 insertions, 1 deletion

dotnet-10-clean-architecture-boilerplate-guide.md

@@ -1,3 +1,801 @@
1 + # The Ultimate .NET 10 Clean Architecture Boilerplate: Step-by-Step Implementation Guide
2 +
3 + This guide is an exhaustive, detail-oriented manual for recreating a .NET 10 Clean Architecture and CQRS boilerplate from scratch. It documents every file in the repository in strict chronological order—you will build the core first, and layer dependencies outward, so you never have to reference a file that doesn't exist yet.
4 +
5 + ## Table of Contents
6 +
7 + 1. [Architecture Overview](#1-architecture-overview)
8 + 2. [Prerequisites & Environment Setup](#2-prerequisites--environment-setup)
9 + 3. [Solution & Project Scaffolding](#3-solution--project-scaffolding)
10 + 4. [Root Configuration Files](#4-root-configuration-files)
11 + 5. [Layer 1: Domain](#5-layer-1-domain)
12 + 6. [Layer 2: Application](#6-layer-2-application)
13 + 7. [Layer 3: Infrastructure](#7-layer-3-infrastructure)
14 + 8. [Layer 4: API / Presentation](#8-layer-4-api--presentation)
15 + 9. [Docker & Dev Environment](#9-docker--dev-environment)
16 + 10. [Test Projects](#10-test-projects)
17 + 11. [CI/CD Pipeline](#11-cicd-pipeline)
18 + 12. [AI-Assisted Development](#12-ai-assisted-development)
19 + 13. [Running the Project](#13-running-the-project)
20 + 14. [Appendix A: Outbox Pattern (Optional)](#appendix-a-outbox-pattern-optional)
21 +
22 + ---
23 +
24 + ## 1. Architecture Overview
25 +
26 + Clean Architecture organises code into concentric layers where dependencies **always point inward**.
27 +
28 + - **Domain** references nothing.
29 + - **Application** references Domain only.
30 + - **Infrastructure** references Application (and transitively, Domain).
31 + - **API** references Application and Infrastructure.
32 +
33 + This guarantees the Domain and Application layers are fully testable without a database, web server, or framework.
34 +
35 + ---
36 +
37 + ## 2. Prerequisites & Environment Setup
38 +
39 + Ensure you have the **.NET 10 SDK**, **Docker**, and your preferred IDE installed.
40 +
41 + To make this guide copy-paste friendly, open your terminal and set your project variables. We use two variables: one for C# PascalCase naming, and one for lowercase systems (Docker/PostgreSQL).
42 +
43 + ```bash
44 + export PROJECT="Inventory"
45 + export PROJECT_LOWER="inventory"
46 + ```
47 +
48 + ---
49 +
50 + ## 3. Solution & Project Scaffolding
51 +
52 + Create the root directory and initialize the solution and projects using your variables:
53 +
54 + ```bash
55 + mkdir ${PROJECT_LOWER}-api
56 + cd ${PROJECT_LOWER}-api
57 +
58 + # Create the solution (slnx = lightweight XML format)
59 + dotnet new slnx -n ${PROJECT}
60 +
61 + # Create the source projects
62 + dotnet new webapi -n ${PROJECT}.Api -o src/${PROJECT}.Api
63 + dotnet new classlib -n ${PROJECT}.Application -o src/${PROJECT}.Application
64 + dotnet new classlib -n ${PROJECT}.Domain -o src/${PROJECT}.Domain
65 + dotnet new classlib -n ${PROJECT}.Infrastructure -o src/${PROJECT}.Infrastructure
66 +
67 + # Create the test projects
68 + dotnet new xunit -n ${PROJECT}.Application.Tests -o tests/${PROJECT}.Application.Tests
69 + dotnet new xunit -n ${PROJECT}.Domain.Tests -o tests/${PROJECT}.Domain.Tests
70 + dotnet new xunit -n ${PROJECT}.IntegrationTests -o tests/${PROJECT}.IntegrationTests
71 +
72 + # Add source projects to the solution
73 + dotnet sln ${PROJECT}.slnx add src/${PROJECT}.Api/${PROJECT}.Api.csproj --solution-folder src
74 + dotnet sln ${PROJECT}.slnx add src/${PROJECT}.Application/${PROJECT}.Application.csproj --solution-folder src
75 + dotnet sln ${PROJECT}.slnx add src/${PROJECT}.Domain/${PROJECT}.Domain.csproj --solution-folder src
76 + dotnet sln ${PROJECT}.slnx add src/${PROJECT}.Infrastructure/${PROJECT}.Infrastructure.csproj --solution-folder src
77 +
78 + # Add test projects to the solution
79 + dotnet sln ${PROJECT}.slnx add tests/${PROJECT}.Application.Tests/${PROJECT}.Application.Tests.csproj --solution-folder tests
80 + dotnet sln ${PROJECT}.slnx add tests/${PROJECT}.Domain.Tests/${PROJECT}.Domain.Tests.csproj --solution-folder tests
81 + dotnet sln ${PROJECT}.slnx add tests/${PROJECT}.IntegrationTests/${PROJECT}.IntegrationTests.csproj --solution-folder tests
82 +
83 + # Configure Clean Architecture Dependencies
84 + dotnet add src/${PROJECT}.Application/${PROJECT}.Application.csproj reference src/${PROJECT}.Domain/${PROJECT}.Domain.csproj
85 + dotnet add src/${PROJECT}.Infrastructure/${PROJECT}.Infrastructure.csproj reference src/${PROJECT}.Application/${PROJECT}.Application.csproj
86 + dotnet add src/${PROJECT}.Api/${PROJECT}.Api.csproj reference src/${PROJECT}.Application/${PROJECT}.Application.csproj
87 + dotnet add src/${PROJECT}.Api/${PROJECT}.Api.csproj reference src/${PROJECT}.Infrastructure/${PROJECT}.Infrastructure.csproj
88 + ```
89 +
90 + ---
91 +
92 + ## 4. Root Configuration Files
93 +
94 + These files lock SDK versions and manage NuGet packages centrally. Create them at the repository root.
95 +
96 + ### `global.json`
97 + ```json
98 + {
99 + "sdk": {
100 + "rollForward": "latestFeature",
101 + "version": "10.0.103"
102 + }
103 + }
104 + ```
105 +
106 + ### `Directory.Build.props`
107 + ```xml
108 + <Project>
109 + <PropertyGroup>
110 + <TargetFramework>net10.0</TargetFramework>
111 + <Nullable>enable</Nullable>
112 + <ImplicitUsings>enable</ImplicitUsings>
113 + <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
114 + </PropertyGroup>
115 + </Project>
116 + ```
117 +
118 + ### `Directory.Packages.props`
119 + ```xml
120 + <Project>
121 + <PropertyGroup>
122 + <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
123 + </PropertyGroup>
124 + <ItemGroup>
125 + <PackageVersion Include="Asp.Versioning.Mvc" Version="10.0.0-preview.2"/>
126 + <PackageVersion Include="Asp.Versioning.Mvc.ApiExplorer" Version="10.0.0-preview.2"/>
127 + <PackageVersion Include="AspNetCore.HealthChecks.NpgSql" Version="9.0.0"/>
128 + <PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.5"/>
129 + <PackageVersion Include="Serilog.AspNetCore" Version="10.0.0"/>
130 + <PackageVersion Include="Serilog.Enrichers.Environment" Version="3.0.1"/>
131 + <PackageVersion Include="Serilog.Enrichers.Thread" Version="4.0.0"/>
132 + <PackageVersion Include="FluentValidation" Version="12.1.1"/>
133 + <PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.1.1"/>
134 + <PackageVersion Include="MediatR" Version="14.1.0"/>
135 + <PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.5"/>
136 + <PackageVersion Include="Newtonsoft.Json" Version="13.0.4"/>
137 + <PackageVersion Include="Quartz.Extensions.Hosting" Version="3.16.1"/>
138 + <PackageVersion Include="Microsoft.EntityFrameworkCore" Version="10.0.5"/>
139 + <PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.5"/>
140 + <PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.5"/>
141 + <PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.1"/>
142 + <PackageVersion Include="coverlet.collector" Version="8.0.0"/>
143 + <PackageVersion Include="FluentAssertions" Version="8.8.0"/>
144 + <PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.5"/>
145 + <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.3.0"/>
146 + <PackageVersion Include="Moq" Version="4.20.72"/>
147 + <PackageVersion Include="xunit" Version="2.9.3"/>
148 + <PackageVersion Include="xunit.runner.visualstudio" Version="3.1.5"/>
149 + </ItemGroup>
150 + </Project>
151 + ```
152 +
153 + ### Apply NuGet Packages to Projects
154 + Now that versioning is centralized, add the packages to your projects.
155 +
156 + ```bash
157 + # Application Layer
158 + dotnet add src/${PROJECT}.Application package MediatR
159 + dotnet add src/${PROJECT}.Application package FluentValidation
160 + dotnet add src/${PROJECT}.Application package FluentValidation.DependencyInjectionExtensions
161 + dotnet add src/${PROJECT}.Application package Microsoft.Extensions.Logging.Abstractions
162 +
163 + # Infrastructure Layer
164 + dotnet add src/${PROJECT}.Infrastructure package Microsoft.EntityFrameworkCore
165 + dotnet add src/${PROJECT}.Infrastructure package Microsoft.EntityFrameworkCore.Design
166 + dotnet add src/${PROJECT}.Infrastructure package Npgsql.EntityFrameworkCore.PostgreSQL
167 + dotnet add src/${PROJECT}.Infrastructure package Newtonsoft.Json
168 + dotnet add src/${PROJECT}.Infrastructure package Quartz.Extensions.Hosting
169 +
170 + # API Layer
171 + dotnet add src/${PROJECT}.Api package Serilog.AspNetCore
172 + dotnet add src/${PROJECT}.Api package Serilog.Enrichers.Environment
173 + dotnet add src/${PROJECT}.Api package Serilog.Enrichers.Thread
174 + dotnet add src/${PROJECT}.Api package AspNetCore.HealthChecks.NpgSql
175 + dotnet add src/${PROJECT}.Api package Microsoft.AspNetCore.OpenApi
176 + dotnet add src/${PROJECT}.Api package Microsoft.EntityFrameworkCore.Tools
177 + dotnet add src/${PROJECT}.Api package Asp.Versioning.Mvc
178 + dotnet add src/${PROJECT}.Api package Asp.Versioning.Mvc.ApiExplorer
179 +
180 + # Test Projects (Domain)
181 + dotnet add tests/${PROJECT}.Domain.Tests package Microsoft.NET.Test.Sdk
182 + dotnet add tests/${PROJECT}.Domain.Tests package xunit
183 + dotnet add tests/${PROJECT}.Domain.Tests package xunit.runner.visualstudio
184 + dotnet add tests/${PROJECT}.Domain.Tests package coverlet.collector
185 + dotnet add tests/${PROJECT}.Domain.Tests package FluentAssertions
186 + dotnet add tests/${PROJECT}.Domain.Tests package Moq
187 +
188 + # Test Projects (Application)
189 + dotnet add tests/${PROJECT}.Application.Tests package Microsoft.NET.Test.Sdk
190 + dotnet add tests/${PROJECT}.Application.Tests package xunit
191 + dotnet add tests/${PROJECT}.Application.Tests package xunit.runner.visualstudio
192 + dotnet add tests/${PROJECT}.Application.Tests package coverlet.collector
193 + dotnet add tests/${PROJECT}.Application.Tests package FluentAssertions
194 + dotnet add tests/${PROJECT}.Application.Tests package Moq
195 +
196 + # Test Projects (Integration)
197 + dotnet add tests/${PROJECT}.IntegrationTests package Microsoft.NET.Test.Sdk
198 + dotnet add tests/${PROJECT}.IntegrationTests package xunit
199 + dotnet add tests/${PROJECT}.IntegrationTests package xunit.runner.visualstudio
200 + dotnet add tests/${PROJECT}.IntegrationTests package coverlet.collector
201 + dotnet add tests/${PROJECT}.IntegrationTests package FluentAssertions
202 + dotnet add tests/${PROJECT}.IntegrationTests package Moq
203 + dotnet add tests/${PROJECT}.IntegrationTests package Microsoft.AspNetCore.Mvc.Testing
204 + ```
205 +
206 + ---
207 +
208 + ## 5. Layer 1: Domain
209 +
210 + *The innermost layer. Contains entities, value objects, domain events, the Result pattern, and repository abstractions. It has **zero** NuGet dependencies.*
211 +
212 + ### `src/${PROJECT}.Domain/Common/IDomainEvent.cs`
213 + ```csharp
214 + namespace ${PROJECT}.Domain.Common;
215 +
216 + public interface IDomainEvent
217 + {
218 + DateTime OccurredOn { get; }
219 + }
220 + ```
221 +
222 + ### `src/${PROJECT}.Domain/Common/BaseEntity.cs`
223 + ```csharp
224 + namespace ${PROJECT}.Domain.Common;
225 +
226 + public abstract class BaseEntity
227 + {
228 + private readonly List<IDomainEvent> _domainEvents = [];
229 + public Guid Id { get; private init; } = Guid.NewGuid();
230 + public IReadOnlyCollection<IDomainEvent> DomainEvents => _domainEvents.AsReadOnly();
231 +
232 + public void AddDomainEvent(IDomainEvent domainEvent) => _domainEvents.Add(domainEvent);
233 + public void RemoveDomainEvent(IDomainEvent domainEvent) => _domainEvents.Remove(domainEvent);
234 + public void ClearDomainEvents() => _domainEvents.Clear();
235 + }
236 + ```
237 +
238 + ### `src/${PROJECT}.Domain/Common/AuditableEntity.cs`
239 + ```csharp
240 + namespace ${PROJECT}.Domain.Common;
241 +
242 + public abstract class AuditableEntity : BaseEntity
243 + {
244 + public DateTime CreatedAt { get; private set; }
245 + public DateTime? UpdatedAt { get; private set; }
246 +
247 + public void SetCreatedAt(DateTime createdAt) => CreatedAt = createdAt;
248 + public void SetUpdatedAt(DateTime updatedAt) => UpdatedAt = updatedAt;
249 + }
250 + ```
251 +
252 + ### `src/${PROJECT}.Domain/Common/Error.cs`
253 + ```csharp
254 + namespace ${PROJECT}.Domain.Common;
255 +
256 + public enum ErrorType { None = 0, Failure = 1, Validation = 2, NotFound = 3, Conflict = 4 }
257 +
258 + public sealed record Error(string Code, string Description, ErrorType Type)
259 + {
260 + public static readonly Error None = new(string.Empty, string.Empty, ErrorType.None);
261 + public static readonly Error NullValue = new("Error.NullValue", "A null value was provided.", ErrorType.Failure);
262 + public static readonly Error NotFound = new("Error.NotFound", "The requested resource was not found.", ErrorType.NotFound);
263 + public static readonly Error Conflict = new("Error.Conflict", "A conflict occurred with the current state.", ErrorType.Conflict);
264 + public static readonly Error Validation = new("Error.Validation", "A validation error occurred.", ErrorType.Validation);
265 + }
266 + ```
267 +
268 + ### `src/${PROJECT}.Domain/Common/Result.cs`
269 + ```csharp
270 + namespace ${PROJECT}.Domain.Common;
271 +
272 + public interface IValidationResult
273 + {
274 + static abstract Result Failure(Error error);
275 + }
276 +
277 + public class Result : IValidationResult
278 + {
279 + protected Result(bool isSuccess, Error error)
280 + {
281 + if (isSuccess && error != Error.None) throw new InvalidOperationException("A successful result cannot have an error.");
282 + if (!isSuccess && error == Error.None) throw new InvalidOperationException("A failed result must have an error.");
283 + IsSuccess = isSuccess;
284 + Error = error;
285 + }
286 +
287 + public bool IsSuccess { get; }
288 + public bool IsFailure => !IsSuccess;
289 + public Error Error { get; }
290 +
291 + public static Result Success() => new(true, Error.None);
292 + public static Result<T> Success<T>(T value) => Result<T>.Success(value);
293 + public static Result Failure(Error error) => new(false, error);
294 + public static Result<T> Failure<T>(Error error) => Result<T>.Failure(error);
295 + }
296 +
297 + public class Result<T> : Result, IValidationResult
298 + {
299 + private readonly T? _value;
300 +
301 + private Result(T? value, bool isSuccess, Error error) : base(isSuccess, error)
302 + {
303 + _value = value;
304 + }
305 +
306 + public T Value => IsSuccess ? _value! : throw new InvalidOperationException("Cannot access the value of a failed result.");
307 +
308 + public static Result<T> Success(T value) => new(value, true, Error.None);
309 + public new static Result<T> Failure(Error error) => new(default, false, error);
310 + public static implicit operator Result<T>(T value) => Success(value);
311 + }
312 + ```
313 +
314 + ### `src/${PROJECT}.Domain/Abstractions/IUnitOfWork.cs`
315 + ```csharp
316 + namespace ${PROJECT}.Domain.Abstractions;
317 +
318 + public interface IUnitOfWork
319 + {
320 + Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
321 + }
322 + ```
323 +
324 + ---
325 +
326 + ## 6. Layer 2: Application
327 +
328 + *Contains use cases (commands, queries, handlers), validation, mapping, and MediatR pipeline behaviors. References Domain only.*
329 +
330 + ### `src/${PROJECT}.Application/Abstractions/Messaging/ICommand.cs`
331 + ```csharp
332 + using MediatR;
333 + using ${PROJECT}.Domain.Common;
334 +
335 + namespace ${PROJECT}.Application.Abstractions.Messaging;
336 +
337 + public interface ICommand : IRequest<Result>;
338 + public interface ICommand<TResponse> : IRequest<Result<TResponse>>;
339 + ```
340 +
341 + ### `src/${PROJECT}.Application/Abstractions/Messaging/ICommandHandler.cs`
342 + ```csharp
343 + using MediatR;
344 + using ${PROJECT}.Domain.Common;
345 +
346 + namespace ${PROJECT}.Application.Abstractions.Messaging;
347 +
348 + public interface ICommandHandler<in TCommand> : IRequestHandler<TCommand, Result> where TCommand : ICommand;
349 + public interface ICommandHandler<in TCommand, TResponse> : IRequestHandler<TCommand, Result<TResponse>> where TCommand : ICommand<TResponse>;
350 + ```
351 +
352 + ### `src/${PROJECT}.Application/Abstractions/IDomainEventHandler.cs`
353 + ```csharp
354 + using MediatR;
355 + using ${PROJECT}.Domain.Common;
356 +
357 + namespace ${PROJECT}.Application.Abstractions;
358 +
359 + public sealed class DomainEventNotification<TDomainEvent>(TDomainEvent domainEvent) : INotification where TDomainEvent : IDomainEvent
360 + {
361 + public TDomainEvent DomainEvent { get; } = domainEvent;
362 + }
363 +
364 + public interface IDomainEventHandler<TDomainEvent> : INotificationHandler<DomainEventNotification<TDomainEvent>> where TDomainEvent : IDomainEvent;
365 + ```
366 +
367 + ### `src/${PROJECT}.Application/Behaviors/LoggingBehavior.cs`
368 + ```csharp
369 + using System.Diagnostics;
370 + using MediatR;
371 + using Microsoft.Extensions.Logging;
372 +
373 + namespace ${PROJECT}.Application.Behaviors;
374 +
375 + public sealed class LoggingBehavior<TRequest, TResponse>(ILogger<LoggingBehavior<TRequest, TResponse>> logger) : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
376 + {
377 + public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
378 + {
379 + var requestName = typeof(TRequest).Name;
380 + logger.LogInformation("Handling {RequestName}", requestName);
381 + var stopwatch = Stopwatch.StartNew();
382 + var response = await next(cancellationToken);
383 + stopwatch.Stop();
384 + logger.LogInformation("Handled {RequestName} in {ElapsedMilliseconds}ms", requestName, stopwatch.ElapsedMilliseconds);
385 + return response;
386 + }
387 + }
388 + ```
389 +
390 + ### `src/${PROJECT}.Application/Behaviors/ValidationBehavior.cs`
391 + ```csharp
392 + using FluentValidation;
393 + using MediatR;
394 + using Microsoft.Extensions.Logging;
395 + using ${PROJECT}.Domain.Common;
396 +
397 + namespace ${PROJECT}.Application.Behaviors;
398 +
399 + public sealed class ValidationBehavior<TRequest, TResponse>(
400 + IEnumerable<IValidator<TRequest>> validators,
401 + ILogger<ValidationBehavior<TRequest, TResponse>> logger)
402 + : IPipelineBehavior<TRequest, TResponse>
403 + where TRequest : IRequest<TResponse>
404 + where TResponse : Result, IValidationResult
405 + {
406 + public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
407 + {
408 + var validatorList = validators as IReadOnlyList<IValidator<TRequest>> ?? [.. validators];
409 +
410 + if (validatorList.Count == 0) return await next(cancellationToken);
411 +
412 + var context = new ValidationContext<TRequest>(request);
413 + var validationResults = await Task.WhenAll(validatorList.Select(v => v.ValidateAsync(context, cancellationToken)));
414 + var failures = validationResults.SelectMany(r => r.Errors).Where(f => f is not null).ToList();
415 +
416 + if (failures.Count != 0)
417 + {
418 + var errorMessage = string.Join("; ", failures.Select(f => f.ErrorMessage));
419 + var error = new Error("Validation", errorMessage, ErrorType.Validation);
420 + logger.LogWarning("Validation failed for {RequestName}: {ErrorMessage}", typeof(TRequest).Name, errorMessage);
421 +
422 + // Direct call to static abstract Failure method. No reflection!
423 + return (TResponse)TResponse.Failure(error);
424 + }
425 +
426 + return await next(cancellationToken);
427 + }
428 + }
429 + ```
430 +
431 + ### `src/${PROJECT}.Application/DependencyInjection.cs`
432 + ```csharp
433 + using FluentValidation;
434 + using MediatR;
435 + using Microsoft.Extensions.DependencyInjection;
436 + using ${PROJECT}.Application.Behaviors;
437 +
438 + namespace ${PROJECT}.Application;
439 +
440 + public static class DependencyInjection
441 + {
442 + public static IServiceCollection AddApplication(this IServiceCollection services)
443 + {
444 + var assembly = typeof(DependencyInjection).Assembly;
445 +
446 + services.AddMediatR(cfg =>
447 + {
448 + cfg.RegisterServicesFromAssembly(assembly);
449 + cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));
450 + cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
451 + });
452 +
453 + services.AddValidatorsFromAssembly(assembly);
454 + return services;
455 + }
456 + }
457 + ```
458 +
459 + ---
460 +
461 + ## 7. Layer 3: Infrastructure
462 +
463 + *Implements the abstractions defined in Domain and Application. Contains the EF Core `DbContext` and interceptors.*
464 +
465 + ### `src/${PROJECT}.Infrastructure/Persistence/Interceptors/AuditableEntityInterceptor.cs`
466 + ```csharp
467 + using Microsoft.EntityFrameworkCore;
468 + using Microsoft.EntityFrameworkCore.Diagnostics;
469 + using ${PROJECT}.Domain.Common;
470 +
471 + namespace ${PROJECT}.Infrastructure.Persistence.Interceptors;
472 +
473 + public sealed class AuditableEntityInterceptor : SaveChangesInterceptor
474 + {
475 + public override ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
476 + {
477 + UpdateAuditableEntities(eventData.Context);
478 + return base.SavingChangesAsync(eventData, result, cancellationToken);
479 + }
480 +
481 + private static void UpdateAuditableEntities(DbContext? context)
482 + {
483 + if (context is null) return;
484 + var utcNow = DateTime.UtcNow;
485 + foreach (var entry in context.ChangeTracker.Entries<AuditableEntity>())
486 + {
487 + if (entry.State == EntityState.Added) entry.Entity.SetCreatedAt(utcNow);
488 + if (entry.State == EntityState.Modified) entry.Entity.SetUpdatedAt(utcNow);
489 + }
490 + }
491 + }
492 + ```
493 +
494 + ### `src/${PROJECT}.Infrastructure/Persistence/Interceptors/DomainEventInterceptor.cs`
495 + ```csharp
496 + using MediatR;
497 + using Microsoft.EntityFrameworkCore;
498 + using Microsoft.EntityFrameworkCore.Diagnostics;
499 + using ${PROJECT}.Application.Abstractions;
500 + using ${PROJECT}.Domain.Common;
501 +
502 + namespace ${PROJECT}.Infrastructure.Persistence.Interceptors;
503 +
504 + public sealed class DomainEventInterceptor(IPublisher publisher) : SaveChangesInterceptor
505 + {
506 + public override async ValueTask<int> SavedChangesAsync(SaveChangesCompletedEventData eventData, int result, CancellationToken cancellationToken = default)
507 + {
508 + if (eventData.Context is not null)
509 + await PublishDomainEventsAsync(eventData.Context, cancellationToken);
510 + return await base.SavedChangesAsync(eventData, result, cancellationToken);
511 + }
512 +
513 + private async Task PublishDomainEventsAsync(DbContext context, CancellationToken cancellationToken)
514 + {
515 + var entities = context.ChangeTracker.Entries<BaseEntity>().Where(e => e.Entity.DomainEvents.Count != 0).Select(e => e.Entity).ToList();
516 + var domainEvents = entities.SelectMany(e => e.DomainEvents).ToList();
517 + entities.ForEach(e => e.ClearDomainEvents());
518 +
519 + foreach (var domainEvent in domainEvents)
520 + {
521 + var notificationType = typeof(DomainEventNotification<>).MakeGenericType(domainEvent.GetType());
522 + var notification = Activator.CreateInstance(notificationType, domainEvent)!;
523 + await publisher.Publish(notification, cancellationToken);
524 + }
525 + }
526 + }
527 + ```
528 +
529 + ### `src/${PROJECT}.Infrastructure/Persistence/ApplicationDbContext.cs`
530 + ```csharp
531 + using Microsoft.EntityFrameworkCore;
532 + using ${PROJECT}.Domain.Abstractions;
533 +
534 + namespace ${PROJECT}.Infrastructure.Persistence;
535 +
536 + public sealed class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : DbContext(options), IUnitOfWork
537 + {
538 + protected override void OnModelCreating(ModelBuilder modelBuilder)
539 + {
540 + modelBuilder.ApplyConfigurationsFromAssembly(typeof(ApplicationDbContext).Assembly);
541 + base.OnModelCreating(modelBuilder);
542 + }
543 + }
544 + ```
545 +
546 + ### `src/${PROJECT}.Infrastructure/DependencyInjection.cs`
547 + ```csharp
548 + using Microsoft.EntityFrameworkCore;
549 + using Microsoft.Extensions.Configuration;
550 + using Microsoft.Extensions.DependencyInjection;
551 + using ${PROJECT}.Domain.Abstractions;
552 + using ${PROJECT}.Infrastructure.Persistence;
553 + using ${PROJECT}.Infrastructure.Persistence.Interceptors;
554 +
555 + namespace ${PROJECT}.Infrastructure;
556 +
557 + public static class DependencyInjection
558 + {
559 + public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
560 + {
561 + services.AddSingleton<AuditableEntityInterceptor>();
562 + services.AddScoped<DomainEventInterceptor>();
563 +
564 + services.AddDbContext<ApplicationDbContext>((sp, options) =>
565 + {
566 + var auditableInterceptor = sp.GetRequiredService<AuditableEntityInterceptor>();
567 + var domainEventInterceptor = sp.GetRequiredService<DomainEventInterceptor>();
568 +
569 + options.UseNpgsql(configuration.GetConnectionString("DefaultConnection"))
570 + .AddInterceptors(auditableInterceptor, domainEventInterceptor);
571 + });
572 +
573 + services.AddScoped<IUnitOfWork>(sp => sp.GetRequiredService<ApplicationDbContext>());
574 +
575 + return services;
576 + }
577 + }
578 + ```
579 +
580 + ---
581 +
582 + ## 8. Layer 4: API / Presentation
583 +
584 + *The composition root where all layers meet. Controllers, Middleware, and Program.cs.*
585 +
586 + ### `src/${PROJECT}.Api/appsettings.json`
587 + ```json
588 + {
589 + "ConnectionStrings": {
590 + "DefaultConnection": ""
591 + },
592 + "Serilog": {
593 + "Using": ["Serilog.Sinks.Console"],
594 + "MinimumLevel": {
595 + "Default": "Information",
596 + "Override": { "Microsoft.AspNetCore": "Warning", "Microsoft.EntityFrameworkCore": "Warning" }
597 + },
598 + "WriteTo": [
599 + { "Name": "Console", "Args": { "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext}{CorrelationId: [{CorrelationId}]} {Message:lj}{NewLine}{Exception}" } }
600 + ],
601 + "Enrich": ["FromLogContext", "WithMachineName", "WithThreadId"]
602 + },
603 + "AllowedHosts": "*"
604 + }
605 + ```
606 +
607 + ### `src/${PROJECT}.Api/Extensions/ServiceCollectionExtensions.cs`
608 + ```csharp
609 + using Asp.Versioning;
610 + using Serilog;
611 + using ${PROJECT}.Application;
612 + using ${PROJECT}.Infrastructure;
613 +
614 + namespace ${PROJECT}.Api.Extensions;
615 +
616 + public static class ServiceCollectionExtensions
617 + {
618 + public static WebApplicationBuilder AddServices(this WebApplicationBuilder builder)
619 + {
620 + builder.Host.UseSerilog((context, loggerConfiguration) =>
621 + loggerConfiguration.ReadFrom.Configuration(context.Configuration));
622 +
623 + builder.Services.AddControllers();
624 + builder.Services.AddOpenApi();
625 + builder.Services.AddProblemDetails();
626 +
627 + builder.Services.AddApiVersioning(options =>
628 + {
629 + options.DefaultApiVersion = new ApiVersion(1, 0);
630 + options.AssumeDefaultVersionWhenUnspecified = true;
631 + options.ReportApiVersions = true;
632 + options.ApiVersionReader = new UrlSegmentApiVersionReader();
633 + })
634 + .AddApiExplorer(options =>
635 + {
636 + options.GroupNameFormat = "'v'VVV";
637 + options.SubstituteApiVersionInUrl = true;
638 + });
639 +
640 + builder.Services.AddApplication();
641 + builder.Services.AddInfrastructure(builder.Configuration);
642 +
643 + var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
644 + ?? throw new InvalidOperationException("Connection string 'DefaultConnection' is not configured.");
645 +
646 + builder.Services.AddHealthChecks().AddNpgSql(connectionString);
647 +
648 + return builder;
649 + }
650 + }
651 + ```
652 +
653 + ### `src/${PROJECT}.Api/Extensions/WebApplicationExtensions.cs`
654 + ```csharp
655 + namespace ${PROJECT}.Api.Extensions;
656 +
657 + public static class WebApplicationExtensions
658 + {
659 + public static WebApplication ConfigurePipeline(this WebApplication app)
660 + {
661 + if (app.Environment.IsDevelopment())
662 + app.MapOpenApi();
663 +
664 + app.UseExceptionHandler();
665 + app.UseHttpsRedirection();
666 + app.UseAuthorization();
667 + app.MapControllers();
668 + app.MapHealthChecks("/health");
669 +
670 + return app;
671 + }
672 + }
673 + ```
674 +
675 + ### `src/${PROJECT}.Api/Program.cs`
676 + ```csharp
677 + using Serilog;
678 + using ${PROJECT}.Api.Extensions;
679 +
680 + var builder = WebApplication.CreateBuilder(args);
681 + builder.AddServices();
682 +
683 + var app = builder.Build();
684 + app.ConfigurePipeline();
685 +
686 + try
687 + {
688 + Log.Information("Starting ${PROJECT} API in {Environment} environment", app.Environment.EnvironmentName);
689 + app.Run();
690 + }
691 + catch (Exception ex)
692 + {
693 + Log.Fatal(ex, "Application terminated unexpectedly");
694 + }
695 + finally
696 + {
697 + Log.CloseAndFlush();
698 + }
699 +
700 + public partial class Program; // Needed for integration tests
701 + ```
702 +
703 + ---
704 +
705 + ## 9. Docker & Dev Environment
706 +
707 + Create these files in your repository root.
708 +
709 + ### `.env.example`
710 + ```bash
711 + DOCKER_IMAGE=your-dockerhub-username/${PROJECT_LOWER}-api
712 + IMAGE_TAG=latest
713 +
714 + ASPNETCORE_ENVIRONMENT=Development
715 + API_PORT=5212
716 +
717 + POSTGRES_DB=${PROJECT_LOWER}_dev
718 + POSTGRES_USER=postgres
719 + POSTGRES_PASSWORD=change-me-to-a-strong-password
720 + DB_PORT=5432
721 +
722 + CONNECTION_STRING=Host=db;Port=5432;Database=${PROJECT_LOWER}_dev;Username=postgres;Password=change-me-to-a-strong-password
723 + ```
724 +
725 + ### `compose.yml`
726 + ```yaml
727 + services:
728 + api:
729 + container_name: ${PROJECT_LOWER}-api
730 + image: ${DOCKER_IMAGE:-${PROJECT_LOWER}-api}:${IMAGE_TAG:-latest}
731 + build:
732 + context: .
733 + dockerfile: Dockerfile
734 + ports:
735 + - "${API_PORT:-5212}:8080"
736 + environment:
737 + - ASPNETCORE_ENVIRONMENT=${ASPNETCORE_ENVIRONMENT:-Development}
738 + - ConnectionStrings__DefaultConnection=${CONNECTION_STRING:-Host=db;Port=5432;Database=${PROJECT_LOWER}_dev;Username=postgres;Password=postgres}
739 + depends_on:
740 + db:
741 + condition: service_healthy
742 +
743 + db:
744 + container_name: ${PROJECT_LOWER}-db
745 + image: postgres:17-alpine
746 + ports:
747 + - "${DB_PORT:-5432}:5432"
748 + environment:
749 + POSTGRES_DB: ${POSTGRES_DB:-${PROJECT_LOWER}_dev}
750 + POSTGRES_USER: ${POSTGRES_USER:-postgres}
751 + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
752 + volumes:
753 + - postgres_data:/var/lib/postgresql/data
754 + healthcheck:
755 + test: ["CMD-SHELL", "pg_isready -U postgres"]
756 + interval: 5s
757 + timeout: 5s
758 + retries: 5
759 +
760 + volumes:
761 + postgres_data:
762 + ```
763 +
764 + ### `Dockerfile`
765 + ```dockerfile
766 + FROM [mcr.microsoft.com/dotnet/aspnet:10.0](https://mcr.microsoft.com/dotnet/aspnet:10.0) AS base
767 + WORKDIR /app
768 + EXPOSE 8080
769 +
770 + FROM [mcr.microsoft.com/dotnet/sdk:10.0](https://mcr.microsoft.com/dotnet/sdk:10.0) AS build
771 + ARG BUILD_CONFIGURATION=Release
772 + WORKDIR /src
773 +
774 + COPY global.json .
775 + COPY Directory.Build.props .
776 + COPY Directory.Packages.props .
777 + COPY src/${PROJECT}.Api/${PROJECT}.Api.csproj src/${PROJECT}.Api/
778 + COPY src/${PROJECT}.Application/${PROJECT}.Application.csproj src/${PROJECT}.Application/
779 + COPY src/${PROJECT}.Domain/${PROJECT}.Domain.csproj src/${PROJECT}.Domain/
780 + COPY src/${PROJECT}.Infrastructure/${PROJECT}.Infrastructure.csproj src/${PROJECT}.Infrastructure/
781 +
782 + RUN dotnet restore src/${PROJECT}.Api/${PROJECT}.Api.csproj
783 +
784 + COPY . .
785 + RUN dotnet build src/${PROJECT}.Api -c $BUILD_CONFIGURATION --no-restore
786 +
787 + FROM build AS publish
788 + ARG BUILD_CONFIGURATION=Release
789 + RUN dotnet publish src/${PROJECT}.Api -c $BUILD_CONFIGURATION --no-build -o /app/publish /p:UseAppHost=false
790 +
791 + FROM base AS final
792 + WORKDIR /app
793 + COPY --from=publish /app/publish .
794 + ENTRYPOINT ["dotnet", "${PROJECT}.Api.dll"]
795 + ```
796 +
797 + ---
798 +
1 799 ## 10. Test Projects
2 800
3 801 ### Test Strategy
@@ -565,4 +1363,5 @@ public sealed class ProcessOutboxMessagesJob(
565 1363 - You need at-least-once delivery guarantees
566 1364 - You're in a microservices architecture where services communicate via events
567 1365
568 - For purely in-process event handling (the common case in a monolith), the existing `DomainEventInterceptor` approach is simpler and sufficient.
1366 + For purely in-process event handling (the common case in a monolith), the existing `DomainEventInterceptor` approach is simpler and sufficient.
1367 + ```

weehong bu gisti düzenledi 5 months ago. Düzenlemeye git

1 file changed, 32 insertions, 2826 deletions

dotnet-10-clean-architecture-boilerplate-guide.md

@@ -1,2774 +1,4 @@
1 - # The Ultimate .NET 10 Clean Architecture Boilerplate: Step-by-Step Implementation Guide
2 -
3 - This guide is an exhaustive, detail-oriented manual for recreating this .NET 10 Clean Architecture and CQRS boilerplate from scratch. It documents every file in the repository — from root-level configuration to Docker setups, middleware, and test scaffolding — so you can understand not just *what* each file does, but *why* it exists.
4 -
5 - ## How to Use This Guide
6 -
7 - - **Prose** uses `{ProjectName}` as a placeholder. Replace it with your actual project name (e.g., `{Projects}`, `Inventory`, `Payments`).
8 - - **Code blocks** use `{Projects}` as the concrete example — the actual project this guide was written for.
9 - - Sections are ordered by dependency: set up root config first, then work inward from Domain → Application → Infrastructure → API.
10 -
11 - ---
12 -
13 - ## Table of Contents
14 -
15 - 1. [Architecture Overview](#1-architecture-overview)
16 - 2. [Design Decisions & Trade-offs](#2-design-decisions--trade-offs)
17 - 3. [Prerequisites](#3-prerequisites)
18 - 4. [Solution & Project Scaffolding](#4-solution--project-scaffolding)
19 - 5. [Root Configuration Files](#5-root-configuration-files)
20 - 6. [Project Files (.csproj)](#6-project-files-csproj)
21 - 7. [Docker & Dev Environment](#7-docker--dev-environment)
22 - 8. [Layer 1: Domain](#8-layer-1-domain)
23 - 9. [Layer 2: Application](#9-layer-2-application)
24 - 10. [Layer 3: Infrastructure](#10-layer-3-infrastructure)
25 - 11. [Layer 4: API / Presentation](#11-layer-4-api--presentation)
26 - 12. [Test Projects](#12-test-projects)
27 - 13. [CI/CD Pipeline](#13-cicd-pipeline)
28 - 14. [AI-Assisted Development](#14-ai-assisted-development)
29 - 15. [Running the Project](#15-running-the-project)
30 -
31 - ---
32 -
33 - ## 1. Architecture Overview
34 -
35 - ### Clean Architecture
36 -
37 - Clean Architecture organises code into concentric layers where dependencies **always point inward**. The innermost layer (Domain) has zero external dependencies; each outer layer may only reference layers closer to the core.
38 -
39 - ```
40 - ┌─────────────────────────────────────────────────────────────┐
41 - │ API / Presentation │
42 - │ Controllers · Middleware · Serilog · OpenAPI · Program.cs │
43 - │ │
44 - │ ┌─────────────────────────────────────────────────────┐ │
45 - │ │ Infrastructure │ │
46 - │ │ EF Core DbContext · Repositories · Interceptors │ │
47 - │ │ │ │
48 - │ │ ┌─────────────────────────────────────────────┐ │ │
49 - │ │ │ Application │ │ │
50 - │ │ │ Commands · Queries · Handlers · Behaviors │ │ │
51 - │ │ │ Validators · Mapping · DI Registration │ │ │
52 - │ │ │ │ │ │
53 - │ │ │ ┌──────────────────────────────────────┐ │ │ │
54 - │ │ │ │ Domain │ │ │ │
55 - │ │ │ │ Entities · Value Objects · Events │ │ │ │
56 - │ │ │ │ Result · Error · Abstractions │ │ │ │
57 - │ │ │ │ (ZERO external dependencies) │ │ │ │
58 - │ │ │ └──────────────────────────────────────┘ │ │ │
59 - │ │ └─────────────────────────────────────────────┘ │ │
60 - │ └─────────────────────────────────────────────────────┘ │
61 - └─────────────────────────────────────────────────────────────┘
62 - ```
63 -
64 - **The Dependency Rule:** Source-code dependencies must point inward. Nothing in an inner circle can reference anything in an outer circle. Concretely:
65 -
66 - - **Domain** references nothing.
67 - - **Application** references Domain only.
68 - - **Infrastructure** references Application (and transitively, Domain).
69 - - **API** references Application and Infrastructure.
70 -
71 - This means the Domain and Application layers are fully testable without a database, web server, or any framework.
72 -
73 - ### Project Dependency Graph
74 -
75 - ```
76 - {ProjectName}.Api
77 - ├── {ProjectName}.Application
78 - │ └── {ProjectName}.Domain (zero NuGet deps)
79 - └── {ProjectName}.Infrastructure
80 - └── {ProjectName}.Application
81 - └── {ProjectName}.Domain
82 -
83 - {ProjectName}.Domain.Tests
84 - └── {ProjectName}.Domain
85 -
86 - {ProjectName}.Application.Tests
87 - └── {ProjectName}.Application
88 -
89 - {ProjectName}.IntegrationTests
90 - └── {ProjectName}.Api
91 - ```
92 -
93 - ### CQRS (Command Query Responsibility Segregation)
94 -
95 - CQRS separates read operations (Queries) from write operations (Commands). Each operation is a standalone class that carries all the data it needs, and each has a dedicated handler. This gives you:
96 -
97 - - **Single Responsibility** — every handler does exactly one thing.
98 - - **Explicit contracts** — the request shape *is* the documentation.
99 - - **Pipeline behaviors** — cross-cutting concerns (logging, validation) are applied uniformly via MediatR's pipeline, not scattered through service classes.
100 -
101 - In this boilerplate, CQRS is implemented through MediatR:
102 -
103 - ```
104 - Controller Handler
105 - │ ▲
106 - │ IMediator.Send(command) │
107 - ▼ │
108 - ┌──────────────────────────────────────────────────┐
109 - │ MediatR Pipeline │
110 - │ │
111 - │ ┌─────────────────┐ ┌──────────────────────┐ │
112 - │ │ LoggingBehavior │──▶│ ValidationBehavior │──┼──▶ Handler
113 - │ └─────────────────┘ └──────────────────────┘ │
114 - └──────────────────────────────────────────────────┘
115 - ```
116 -
117 - Controllers never call services directly. They send a command or query to `IMediator`, which routes it through the pipeline behaviors and into the correct handler.
118 -
119 - ### The Result Pattern
120 -
121 - Instead of throwing exceptions for expected failures (validation errors, not-found, conflicts), every handler returns a `Result` or `Result<T>`. This makes the success/failure path explicit in the type system:
122 -
123 - ```csharp
124 - // Handler returns Result<Guid>, not just Guid
125 - public async Task<Result<Guid>> Handle(CreateMatchCommand request, CancellationToken ct)
126 - {
127 - // Failure path — no exception thrown
128 - if (exists) return Result.Failure<Guid>(Error.Conflict);
129 -
130 - // Success path
131 - return Result.Success(match.Id);
132 - }
133 - ```
134 -
135 - The `IValidationResult` interface with a `static abstract` method enables the `ValidationBehavior` to create typed failure results without reflection — a zero-reflection, high-performance validation pipeline.
136 -
137 - ### MediatR Pipeline Behaviors
138 -
139 - Pipeline behaviors are middleware that wrap every MediatR request. They execute in registration order, forming a chain:
140 -
141 - 1. **LoggingBehavior** — logs the request name and execution time.
142 - 2. **ValidationBehavior** — runs all FluentValidation validators for the request. If any fail, it short-circuits and returns a `Result.Failure` without ever reaching the handler.
143 -
144 - You can add more behaviors (e.g., authorization, caching, transaction management) by registering additional `IPipelineBehavior<,>` implementations.
145 -
146 - ---
147 -
148 - ## 2. Design Decisions & Trade-offs
149 -
150 - | Decision | Why | Alternatives Considered |
151 - |---|---|---|
152 - | **Central Package Management (CPM)** | Single `Directory.Packages.props` controls all NuGet versions — no version drift between projects | Per-project `<PackageVersion>` attributes |
153 - | **Result pattern over exceptions** | Makes success/failure explicit in return types; eliminates try/catch ceremony in callers; no stack-trace overhead for expected failures | Throwing domain exceptions; `OneOf<T>` discriminated unions |
154 - | **MediatR for CQRS** | Decouples controllers from handlers; pipeline behaviors give free cross-cutting concerns; widely adopted in .NET ecosystem | Hand-rolled mediator; direct service injection; Wolverine |
155 - | **`static abstract` on IValidationResult** | Enables `ValidationBehavior` to create typed `Result.Failure` without reflection or `Activator.CreateInstance` | Reflection-based factory; generic constraints with `new()` |
156 - | **Manual mapping (extension methods)** | Zero magic, fully debuggable, no hidden runtime behavior; keeps mapping close to the feature that uses it | AutoMapper; Mapster |
157 - | **FluentValidation** | Declarative, composable rules; integrates cleanly with MediatR pipeline | Data Annotations; hand-rolled validation |
158 - | **Serilog** | Structured logging with rich sink ecosystem; configuration-driven via `appsettings.json` | Built-in `ILogger` with console provider; NLog; log4net |
159 - | **EF Core Interceptors** | Keeps audit (`CreatedAt`/`UpdatedAt`) and domain event dispatch out of the DbContext, making them composable and testable | Overriding `SaveChangesAsync` directly; domain event outbox pattern |
160 - | **API Versioning (URL path segment)** | Non-breaking evolution of APIs; URL path (`/api/v1/`) is the most explicit and cache-friendly strategy; `Asp.Versioning.Mvc` is the official Microsoft-maintained library | Query string versioning; header versioning; no versioning |
161 - | **C# 13 (via .NET 10)** | Latest language version: collection expressions, `static abstract` interfaces, primary constructors, file-scoped namespaces, etc. | Pinning an older `LangVersion` |
162 - | **`.slnx` (XML solution file)** | New lightweight format; cleaner diffs than `.sln`; created directly via `dotnet new slnx` | Traditional `.sln` |
163 - | **PostgreSQL** | Open-source, production-grade RDBMS; excellent JSON support; strong EF Core provider | SQL Server; SQLite (dev-only); MySQL |
164 - | **Quartz.NET** | Mature, cron-capable job scheduler for background tasks (email, cleanup, etc.) | Hangfire; `IHostedService` with `Timer`; custom `BackgroundService` |
165 - | **`compose.yml` (not `docker-compose.yml`)** | Docker Compose V2 standard; shorter name; `docker compose` CLI (no hyphen) | Legacy `docker-compose.yml` |
166 - | **Multi-stage Dockerfile** | Separates build and runtime images; final image contains only published output (~200 MB vs ~1.5 GB) | Single-stage build; publishing locally and copying artifacts |
167 - | **Correlation ID middleware** | Traces a request across services and log entries; accepts client-supplied IDs or generates new ones | W3C Trace Context; OpenTelemetry baggage (heavier) |
168 - | **Sensitive data redaction** | Prevents passwords, tokens, and PII from appearing in logs; JSON DOM + regex fallback handles truncated bodies | Manual redaction per log call; not logging bodies at all |
169 -
170 - ---
171 -
172 - ## 3. Prerequisites
173 -
174 - Ensure you have the following installed:
175 - - **.NET 10 SDK** (Version 10.0.103 or higher)
176 - - **Docker & Docker Compose** (for PostgreSQL and containerization)
177 - - **IDE**: Visual Studio, Rider, or VS Code
178 -
179 - ---
180 -
181 - ## 4. Solution & Project Scaffolding
182 -
183 - Create the root directory and initialize the solution and projects:
184 -
185 - ```bash
186 - mkdir {projectname}-api
187 - cd {projectname}-api
188 -
189 - # Create the solution (slnx = lightweight XML format, cleaner diffs than .sln)
190 - dotnet new slnx -n {Projects}
191 -
192 - # Create the source projects
193 - dotnet new webapi -n {Projects}.Api -o src/{Projects}.Api
194 - dotnet new classlib -n {Projects}.Application -o src/{Projects}.Application
195 - dotnet new classlib -n {Projects}.Domain -o src/{Projects}.Domain
196 - dotnet new classlib -n {Projects}.Infrastructure -o src/{Projects}.Infrastructure
197 -
198 - # Create the test projects
199 - dotnet new xunit -n {Projects}.Application.Tests -o tests/{Projects}.Application.Tests
200 - dotnet new xunit -n {Projects}.Domain.Tests -o tests/{Projects}.Domain.Tests
201 - dotnet new xunit -n {Projects}.IntegrationTests -o tests/{Projects}.IntegrationTests
202 -
203 - # Add source projects to the solution
204 - dotnet sln {Projects}.slnx add src/{Projects}.Api/{Projects}.Api.csproj --solution-folder src
205 - dotnet sln {Projects}.slnx add src/{Projects}.Application/{Projects}.Application.csproj --solution-folder src
206 - dotnet sln {Projects}.slnx add src/{Projects}.Domain/{Projects}.Domain.csproj --solution-folder src
207 - dotnet sln {Projects}.slnx add src/{Projects}.Infrastructure/{Projects}.Infrastructure.csproj --solution-folder src
208 -
209 - # Add test projects to the solution
210 - dotnet sln {Projects}.slnx add tests/{Projects}.Application.Tests/{Projects}.Application.Tests.csproj --solution-folder tests
211 - dotnet sln {Projects}.slnx add tests/{Projects}.Domain.Tests/{Projects}.Domain.Tests.csproj --solution-folder tests
212 - dotnet sln {Projects}.slnx add tests/{Projects}.IntegrationTests/{Projects}.IntegrationTests.csproj --solution-folder tests
213 -
214 - # Configure Clean Architecture Dependencies
215 - dotnet add src/{Projects}.Application/{Projects}.Application.csproj reference src/{Projects}.Domain/{Projects}.Domain.csproj
216 - dotnet add src/{Projects}.Infrastructure/{Projects}.Infrastructure.csproj reference src/{Projects}.Application/{Projects}.Application.csproj
217 - dotnet add src/{Projects}.Api/{Projects}.Api.csproj reference src/{Projects}.Application/{Projects}.Application.csproj
218 - dotnet add src/{Projects}.Api/{Projects}.Api.csproj reference src/{Projects}.Infrastructure/{Projects}.Infrastructure.csproj
219 - ```
220 -
221 - ### Resulting `{ProjectName}.slnx`
222 -
223 - The `dotnet new slnx` command creates the lightweight XML-based solution format directly — no migration from `.sln` needed. The resulting file is concise:
224 -
225 - ```xml
226 - <Solution>
227 - <Folder Name="/src/">
228 - <Project Path="src/{Projects}.Api/{Projects}.Api.csproj"/>
229 - <Project Path="src/{Projects}.Application/{Projects}.Application.csproj"/>
230 - <Project Path="src/{Projects}.Domain/{Projects}.Domain.csproj"/>
231 - <Project Path="src/{Projects}.Infrastructure/{Projects}.Infrastructure.csproj"/>
232 - </Folder>
233 - <Folder Name="/tests/">
234 - <Project Path="tests/{Projects}.Application.Tests/{Projects}.Application.Tests.csproj"/>
235 - <Project Path="tests/{Projects}.Domain.Tests/{Projects}.Domain.Tests.csproj"/>
236 - <Project Path="tests/{Projects}.IntegrationTests/{Projects}.IntegrationTests.csproj"/>
237 - </Folder>
238 - </Solution>
239 - ```
240 -
241 - ---
242 -
243 - ## 5. Root Configuration Files
244 -
245 - These files enforce consistency, lock SDK versions, and centrally manage NuGet packages across all projects. Create them at the repository root (next to the `.slnx` file).
246 -
247 - ### `global.json`
248 -
249 - Locks the .NET SDK version so every developer and CI runner uses the same toolchain. The `rollForward: latestFeature` policy allows patch updates within the 10.0.1xx band but prevents major/minor surprises.
250 -
251 - ```json
252 - {
253 - "sdk": {
254 - "rollForward": "latestFeature",
255 - "version": "10.0.103"
256 - }
257 - }
258 - ```
259 -
260 - ### `Directory.Build.props`
261 -
262 - MSBuild imports this file automatically into every `.csproj` in the repo tree. It sets the target framework, enables nullable reference types, implicit usings, and treats warnings as errors — so no project can accidentally diverge from these defaults.
263 -
264 - ```xml
265 - <Project>
266 - <PropertyGroup>
267 - <TargetFramework>net10.0</TargetFramework>
268 - <Nullable>enable</Nullable>
269 - <ImplicitUsings>enable</ImplicitUsings>
270 - <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
271 - </PropertyGroup>
272 - </Project>
273 - ```
274 -
275 - ### `Directory.Packages.props`
276 -
277 - Enables Central Package Management (CPM). Every NuGet package version is declared once here. Individual `.csproj` files reference packages by name only (no `Version` attribute). This eliminates version drift across projects and makes upgrades a single-file change.
278 -
279 - ```xml
280 - <Project>
281 -
282 - <PropertyGroup>
283 - <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
284 - </PropertyGroup>
285 -
286 - <ItemGroup>
287 - <!-- Web & API -->
288 - <PackageVersion Include="Asp.Versioning.Mvc" Version="10.0.0-preview.2"/>
289 - <PackageVersion Include="Asp.Versioning.Mvc.ApiExplorer" Version="10.0.0-preview.2"/>
290 - <PackageVersion Include="AspNetCore.HealthChecks.NpgSql" Version="9.0.0"/>
291 - <PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.5"/>
292 -
293 - <!-- Logging -->
294 - <PackageVersion Include="Serilog.AspNetCore" Version="10.0.0"/>
295 - <PackageVersion Include="Serilog.Enrichers.Environment" Version="3.0.1"/>
296 - <PackageVersion Include="Serilog.Enrichers.Thread" Version="4.0.0"/>
297 -
298 - <!-- Application -->
299 - <PackageVersion Include="FluentValidation" Version="12.1.1"/>
300 - <PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.1.1"/>
301 - <PackageVersion Include="MediatR" Version="14.1.0"/>
302 - <PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.5"/>
303 -
304 - <!-- Infrastructure -->
305 - <PackageVersion Include="Newtonsoft.Json" Version="13.0.4"/>
306 - <PackageVersion Include="Quartz.Extensions.Hosting" Version="3.16.1"/>
307 -
308 - <!-- Entity Framework Core -->
309 - <PackageVersion Include="Microsoft.EntityFrameworkCore" Version="10.0.5"/>
310 - <PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.5"/>
311 - <PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.5"/>
312 - <PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.1"/>
313 -
314 - <!-- Testing -->
315 - <PackageVersion Include="coverlet.collector" Version="8.0.0"/>
316 - <PackageVersion Include="FluentAssertions" Version="8.8.0"/>
317 - <PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.5"/>
318 - <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.3.0"/>
319 - <PackageVersion Include="Moq" Version="4.20.72"/>
320 - <PackageVersion Include="xunit" Version="2.9.3"/>
321 - <PackageVersion Include="xunit.runner.visualstudio" Version="3.1.5"/>
322 - </ItemGroup>
323 -
324 - </Project>
325 - ```
326 -
327 - ### `nuget.config`
328 -
329 - Explicitly clears any inherited package sources and sets the official NuGet feed as the only source. This prevents builds from silently pulling packages from unexpected feeds (e.g., a corporate proxy or local cache).
330 -
331 - ```xml
332 - <?xml version="1.0" encoding="utf-8"?>
333 - <configuration>
334 - <packageSources>
335 - <clear />
336 - <add key="nuget" value="https://api.nuget.org/v3/index.json" />
337 - </packageSources>
338 - </configuration>
339 - ```
340 -
341 - ### `.editorconfig`
342 -
343 - Enforces consistent code style across all editors and IDEs. The C# section is particularly important — it mandates file-scoped namespaces, `var` usage, and naming conventions (e.g., `_camelCase` for private fields, `I` prefix for interfaces). These rules integrate with Roslyn analyzers, so violations appear as warnings during build.
344 -
345 - ```editorconfig
346 - root = true
347 -
348 - # All files
349 - [*]
350 - indent_style = space
351 -
352 - # Xml files
353 - [*.{xml,csproj,props,targets,ruleset,nuspec,resx}]
354 - indent_size = 2
355 -
356 - # Javascript files
357 - [*.js]
358 - indent_size = 2
359 -
360 - # Json files
361 - [*.{json,config,nswag}]
362 - indent_size = 2
363 -
364 - # C# files
365 - [*.cs]
366 -
367 - #### Core EditorConfig Options ####
368 -
369 - # Indentation and spacing
370 - indent_size = 4
371 - tab_width = 4
372 -
373 - # New line preferences
374 - end_of_line = lf
375 - insert_final_newline = true
376 -
377 - #### .NET Coding Conventions ####
378 - [*.{cs,vb}]
379 -
380 - # Organize usings
381 - dotnet_separate_import_directive_groups = false
382 - dotnet_sort_system_directives_first = true
383 - file_header_template = unset
384 -
385 - # this. and Me. preferences
386 - dotnet_style_qualification_for_event = false:silent
387 - dotnet_style_qualification_for_field = false:silent
388 - dotnet_style_qualification_for_method = false:silent
389 - dotnet_style_qualification_for_property = false:silent
390 -
391 - # Language keywords vs BCL types preferences
392 - dotnet_style_predefined_type_for_locals_parameters_members = true:silent
393 - dotnet_style_predefined_type_for_member_access = true:silent
394 -
395 - # Parentheses preferences
396 - dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent
397 - dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent
398 - dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent
399 - dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent
400 -
401 - # Modifier preferences
402 - dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent
403 -
404 - # Expression-level preferences
405 - dotnet_style_coalesce_expression = true:suggestion
406 - dotnet_style_collection_initializer = true:suggestion
407 - dotnet_style_explicit_tuple_names = true:suggestion
408 - dotnet_style_null_propagation = true:suggestion
409 - dotnet_style_object_initializer = true:suggestion
410 - dotnet_style_operator_placement_when_wrapping = beginning_of_line
411 - dotnet_style_prefer_auto_properties = true:suggestion
412 - dotnet_style_prefer_compound_assignment = true:suggestion
413 - dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion
414 - dotnet_style_prefer_conditional_expression_over_return = true:suggestion
415 - dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
416 - dotnet_style_prefer_inferred_tuple_names = true:suggestion
417 - dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
418 - dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
419 - dotnet_style_prefer_simplified_interpolation = true:suggestion
420 -
421 - # Field preferences
422 - dotnet_style_readonly_field = true:warning
423 -
424 - # Parameter preferences
425 - dotnet_code_quality_unused_parameters = all:suggestion
426 -
427 - # Suppression preferences
428 - dotnet_remove_unnecessary_suppression_exclusions = none
429 -
430 - #### C# Coding Conventions ####
431 - [*.cs]
432 -
433 - # var preferences
434 - csharp_style_var_elsewhere = false:silent
435 - csharp_style_var_for_built_in_types = false:silent
436 - csharp_style_var_when_type_is_apparent = true:suggestion
437 -
438 - # Expression-bodied members
439 - csharp_style_expression_bodied_accessors = true:silent
440 - csharp_style_expression_bodied_constructors = true:suggestion
441 - csharp_style_expression_bodied_indexers = true:silent
442 - csharp_style_expression_bodied_lambdas = true:suggestion
443 - csharp_style_expression_bodied_local_functions = true:suggestion
444 - csharp_style_expression_bodied_methods = true:suggestion
445 - csharp_style_expression_bodied_operators = true:suggestion
446 - csharp_style_expression_bodied_properties = true:silent
447 -
448 - # Pattern matching preferences
449 - csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
450 - csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
451 - csharp_style_prefer_not_pattern = true:suggestion
452 - csharp_style_prefer_pattern_matching = true:silent
453 - csharp_style_prefer_switch_expression = true:suggestion
454 -
455 - # Null-checking preferences
456 - csharp_style_conditional_delegate_call = true:suggestion
457 -
458 - # Modifier preferences
459 - csharp_prefer_static_local_function = true:warning
460 - csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:silent
461 -
462 - # Code-block preferences
463 - csharp_prefer_braces = true:silent
464 - csharp_prefer_simple_using_statement = true:suggestion
465 -
466 - # Expression-level preferences
467 - csharp_prefer_simple_default_expression = true:suggestion
468 - csharp_style_deconstructed_variable_declaration = true:suggestion
469 - csharp_style_inlined_variable_declaration = true:suggestion
470 - csharp_style_pattern_local_over_anonymous_function = true:suggestion
471 - csharp_style_prefer_index_operator = true:suggestion
472 - csharp_style_prefer_range_operator = true:suggestion
473 - csharp_style_throw_expression = true:suggestion
474 - csharp_style_unused_value_assignment_preference = discard_variable:suggestion
475 - csharp_style_unused_value_expression_statement_preference = discard_variable:silent
476 -
477 - # 'using' directive preferences
478 - csharp_using_directive_placement = outside_namespace:silent
479 -
480 - #### C# Formatting Rules ####
481 -
482 - # New line preferences
483 - csharp_new_line_before_catch = true
484 - csharp_new_line_before_else = true
485 - csharp_new_line_before_finally = true
486 - csharp_new_line_before_members_in_anonymous_types = true
487 - csharp_new_line_before_members_in_object_initializers = true
488 - csharp_new_line_before_open_brace = all
489 - csharp_new_line_between_query_expression_clauses = true
490 -
491 - # Indentation preferences
492 - csharp_indent_block_contents = true
493 - csharp_indent_braces = false
494 - csharp_indent_case_contents = true
495 - csharp_indent_case_contents_when_block = true
496 - csharp_indent_labels = one_less_than_current
497 - csharp_indent_switch_labels = true
498 -
499 - # Space preferences
500 - csharp_space_after_cast = false
501 - csharp_space_after_colon_in_inheritance_clause = true
502 - csharp_space_after_comma = true
503 - csharp_space_after_dot = false
504 - csharp_space_after_keywords_in_control_flow_statements = true
505 - csharp_space_after_semicolon_in_for_statement = true
506 - csharp_space_around_binary_operators = before_and_after
507 - csharp_space_around_declaration_statements = false
508 - csharp_space_before_colon_in_inheritance_clause = true
509 - csharp_space_before_comma = false
510 - csharp_space_before_dot = false
511 - csharp_space_before_open_square_brackets = false
512 - csharp_space_before_semicolon_in_for_statement = false
513 - csharp_space_between_empty_square_brackets = false
514 - csharp_space_between_method_call_empty_parameter_list_parentheses = false
515 - csharp_space_between_method_call_name_and_opening_parenthesis = false
516 - csharp_space_between_method_call_parameter_list_parentheses = false
517 - csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
518 - csharp_space_between_method_declaration_name_and_open_parenthesis = false
519 - csharp_space_between_method_declaration_parameter_list_parentheses = false
520 - csharp_space_between_parentheses = false
521 - csharp_space_between_square_brackets = false
522 -
523 - # Wrapping preferences
524 - csharp_preserve_single_line_blocks = true
525 - csharp_preserve_single_line_statements = true
526 - csharp_style_namespace_declarations = file_scoped:suggestion
527 - csharp_style_prefer_method_group_conversion = true:silent
528 - csharp_style_prefer_top_level_statements = true:silent
529 - csharp_style_prefer_primary_constructors = true:warning
530 - csharp_style_prefer_null_check_over_type_check = true:suggestion
531 - csharp_style_prefer_local_over_anonymous_function = true:suggestion
532 - csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion
533 - csharp_style_prefer_tuple_swap = true:suggestion
534 - csharp_style_prefer_utf8_string_literals = true:suggestion
535 -
536 - #### Naming styles ####
537 - [*.{cs,vb}]
538 -
539 - # Naming rules
540 -
541 - dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.severity = suggestion
542 - dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.symbols = types_and_namespaces
543 - dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.style = pascalcase
544 -
545 - dotnet_naming_rule.interfaces_should_be_ipascalcase.severity = suggestion
546 - dotnet_naming_rule.interfaces_should_be_ipascalcase.symbols = interfaces
547 - dotnet_naming_rule.interfaces_should_be_ipascalcase.style = ipascalcase
548 -
549 - dotnet_naming_rule.type_parameters_should_be_tpascalcase.severity = suggestion
550 - dotnet_naming_rule.type_parameters_should_be_tpascalcase.symbols = type_parameters
551 - dotnet_naming_rule.type_parameters_should_be_tpascalcase.style = tpascalcase
552 -
553 - dotnet_naming_rule.methods_should_be_pascalcase.severity = suggestion
554 - dotnet_naming_rule.methods_should_be_pascalcase.symbols = methods
555 - dotnet_naming_rule.methods_should_be_pascalcase.style = pascalcase
556 -
557 - dotnet_naming_rule.properties_should_be_pascalcase.severity = suggestion
558 - dotnet_naming_rule.properties_should_be_pascalcase.symbols = properties
559 - dotnet_naming_rule.properties_should_be_pascalcase.style = pascalcase
560 -
561 - dotnet_naming_rule.events_should_be_pascalcase.severity = suggestion
562 - dotnet_naming_rule.events_should_be_pascalcase.symbols = events
563 - dotnet_naming_rule.events_should_be_pascalcase.style = pascalcase
564 -
565 - dotnet_naming_rule.local_variables_should_be_camelcase.severity = suggestion
566 - dotnet_naming_rule.local_variables_should_be_camelcase.symbols = local_variables
567 - dotnet_naming_rule.local_variables_should_be_camelcase.style = camelcase
568 -
569 - dotnet_naming_rule.local_constants_should_be_camelcase.severity = suggestion
570 - dotnet_naming_rule.local_constants_should_be_camelcase.symbols = local_constants
571 - dotnet_naming_rule.local_constants_should_be_camelcase.style = camelcase
572 -
573 - dotnet_naming_rule.parameters_should_be_camelcase.severity = suggestion
574 - dotnet_naming_rule.parameters_should_be_camelcase.symbols = parameters
575 - dotnet_naming_rule.parameters_should_be_camelcase.style = camelcase
576 -
577 - dotnet_naming_rule.public_fields_should_be_pascalcase.severity = suggestion
578 - dotnet_naming_rule.public_fields_should_be_pascalcase.symbols = public_fields
579 - dotnet_naming_rule.public_fields_should_be_pascalcase.style = pascalcase
580 -
581 - dotnet_naming_rule.private_fields_should_be__camelcase.severity = suggestion
582 - dotnet_naming_rule.private_fields_should_be__camelcase.symbols = private_fields
583 - dotnet_naming_rule.private_fields_should_be__camelcase.style = _camelcase
584 -
585 - dotnet_naming_rule.private_static_fields_should_be_s_camelcase.severity = suggestion
586 - dotnet_naming_rule.private_static_fields_should_be_s_camelcase.symbols = private_static_fields
587 - dotnet_naming_rule.private_static_fields_should_be_s_camelcase.style = s_camelcase
588 -
589 - dotnet_naming_rule.public_constant_fields_should_be_pascalcase.severity = suggestion
590 - dotnet_naming_rule.public_constant_fields_should_be_pascalcase.symbols = public_constant_fields
591 - dotnet_naming_rule.public_constant_fields_should_be_pascalcase.style = pascalcase
592 -
593 - dotnet_naming_rule.private_constant_fields_should_be_pascalcase.severity = suggestion
594 - dotnet_naming_rule.private_constant_fields_should_be_pascalcase.symbols = private_constant_fields
595 - dotnet_naming_rule.private_constant_fields_should_be_pascalcase.style = pascalcase
596 -
597 - dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.severity = suggestion
598 - dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.symbols = public_static_readonly_fields
599 - dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.style = pascalcase
600 -
601 - dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.severity = suggestion
602 - dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.symbols = private_static_readonly_fields
603 - dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.style = pascalcase
604 -
605 - dotnet_naming_rule.enums_should_be_pascalcase.severity = suggestion
606 - dotnet_naming_rule.enums_should_be_pascalcase.symbols = enums
607 - dotnet_naming_rule.enums_should_be_pascalcase.style = pascalcase
608 -
609 - dotnet_naming_rule.local_functions_should_be_pascalcase.severity = suggestion
610 - dotnet_naming_rule.local_functions_should_be_pascalcase.symbols = local_functions
611 - dotnet_naming_rule.local_functions_should_be_pascalcase.style = pascalcase
612 -
613 - dotnet_naming_rule.non_field_members_should_be_pascalcase.severity = suggestion
614 - dotnet_naming_rule.non_field_members_should_be_pascalcase.symbols = non_field_members
615 - dotnet_naming_rule.non_field_members_should_be_pascalcase.style = pascalcase
616 -
617 - # Symbol specifications
618 -
619 - dotnet_naming_symbols.interfaces.applicable_kinds = interface
620 - dotnet_naming_symbols.interfaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
621 - dotnet_naming_symbols.interfaces.required_modifiers =
622 -
623 - dotnet_naming_symbols.enums.applicable_kinds = enum
624 - dotnet_naming_symbols.enums.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
625 - dotnet_naming_symbols.enums.required_modifiers =
626 -
627 - dotnet_naming_symbols.events.applicable_kinds = event
628 - dotnet_naming_symbols.events.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
629 - dotnet_naming_symbols.events.required_modifiers =
630 -
631 - dotnet_naming_symbols.methods.applicable_kinds = method
632 - dotnet_naming_symbols.methods.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
633 - dotnet_naming_symbols.methods.required_modifiers =
634 -
635 - dotnet_naming_symbols.properties.applicable_kinds = property
636 - dotnet_naming_symbols.properties.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
637 - dotnet_naming_symbols.properties.required_modifiers =
638 -
639 - dotnet_naming_symbols.public_fields.applicable_kinds = field
640 - dotnet_naming_symbols.public_fields.applicable_accessibilities = public, internal
641 - dotnet_naming_symbols.public_fields.required_modifiers =
642 -
643 - dotnet_naming_symbols.private_fields.applicable_kinds = field
644 - dotnet_naming_symbols.private_fields.applicable_accessibilities = private, protected, protected_internal, private_protected
645 - dotnet_naming_symbols.private_fields.required_modifiers =
646 -
647 - dotnet_naming_symbols.private_static_fields.applicable_kinds = field
648 - dotnet_naming_symbols.private_static_fields.applicable_accessibilities = private, protected, protected_internal, private_protected
649 - dotnet_naming_symbols.private_static_fields.required_modifiers = static
650 -
651 - dotnet_naming_symbols.types_and_namespaces.applicable_kinds = namespace, class, struct, interface, enum
652 - dotnet_naming_symbols.types_and_namespaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
653 - dotnet_naming_symbols.types_and_namespaces.required_modifiers =
654 -
655 - dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
656 - dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
657 - dotnet_naming_symbols.non_field_members.required_modifiers =
658 -
659 - dotnet_naming_symbols.type_parameters.applicable_kinds = type_parameter
660 - dotnet_naming_symbols.type_parameters.applicable_accessibilities = *
661 - dotnet_naming_symbols.type_parameters.required_modifiers =
662 -
663 - dotnet_naming_symbols.private_constant_fields.applicable_kinds = field
664 - dotnet_naming_symbols.private_constant_fields.applicable_accessibilities = private, protected, protected_internal, private_protected
665 - dotnet_naming_symbols.private_constant_fields.required_modifiers = const
666 -
667 - dotnet_naming_symbols.local_variables.applicable_kinds = local
668 - dotnet_naming_symbols.local_variables.applicable_accessibilities = local
669 - dotnet_naming_symbols.local_variables.required_modifiers =
670 -
671 - dotnet_naming_symbols.local_constants.applicable_kinds = local
672 - dotnet_naming_symbols.local_constants.applicable_accessibilities = local
673 - dotnet_naming_symbols.local_constants.required_modifiers = const
674 -
675 - dotnet_naming_symbols.parameters.applicable_kinds = parameter
676 - dotnet_naming_symbols.parameters.applicable_accessibilities = *
677 - dotnet_naming_symbols.parameters.required_modifiers =
678 -
679 - dotnet_naming_symbols.public_constant_fields.applicable_kinds = field
680 - dotnet_naming_symbols.public_constant_fields.applicable_accessibilities = public, internal
681 - dotnet_naming_symbols.public_constant_fields.required_modifiers = const
682 -
683 - dotnet_naming_symbols.public_static_readonly_fields.applicable_kinds = field
684 - dotnet_naming_symbols.public_static_readonly_fields.applicable_accessibilities = public, internal
685 - dotnet_naming_symbols.public_static_readonly_fields.required_modifiers = readonly, static
686 -
687 - dotnet_naming_symbols.private_static_readonly_fields.applicable_kinds = field
688 - dotnet_naming_symbols.private_static_readonly_fields.applicable_accessibilities = private, protected, protected_internal, private_protected
689 - dotnet_naming_symbols.private_static_readonly_fields.required_modifiers = readonly, static
690 -
691 - dotnet_naming_symbols.local_functions.applicable_kinds = local_function
692 - dotnet_naming_symbols.local_functions.applicable_accessibilities = *
693 - dotnet_naming_symbols.local_functions.required_modifiers =
694 -
695 - # Naming styles
696 -
697 - dotnet_naming_style.pascalcase.required_prefix =
698 - dotnet_naming_style.pascalcase.required_suffix =
699 - dotnet_naming_style.pascalcase.word_separator =
700 - dotnet_naming_style.pascalcase.capitalization = pascal_case
701 -
702 - dotnet_naming_style.ipascalcase.required_prefix = I
703 - dotnet_naming_style.ipascalcase.required_suffix =
704 - dotnet_naming_style.ipascalcase.word_separator =
705 - dotnet_naming_style.ipascalcase.capitalization = pascal_case
706 -
707 - dotnet_naming_style.tpascalcase.required_prefix = T
708 - dotnet_naming_style.tpascalcase.required_suffix =
709 - dotnet_naming_style.tpascalcase.word_separator =
710 - dotnet_naming_style.tpascalcase.capitalization = pascal_case
711 -
712 - dotnet_naming_style._camelcase.required_prefix = _
713 - dotnet_naming_style._camelcase.required_suffix =
714 - dotnet_naming_style._camelcase.word_separator =
715 - dotnet_naming_style._camelcase.capitalization = camel_case
716 -
717 - dotnet_naming_style.camelcase.required_prefix =
718 - dotnet_naming_style.camelcase.required_suffix =
719 - dotnet_naming_style.camelcase.word_separator =
720 - dotnet_naming_style.camelcase.capitalization = camel_case
721 -
722 - dotnet_naming_style.s_camelcase.required_prefix = s_
723 - dotnet_naming_style.s_camelcase.required_suffix =
724 - dotnet_naming_style.s_camelcase.word_separator =
725 - dotnet_naming_style.s_camelcase.capitalization = camel_case
726 -
727 - dotnet_style_namespace_match_folder = true:suggestion
728 - ```
729 -
730 - ### `.dockerignore`
731 -
732 - Tells Docker which files to exclude from the build context. Keeping the context small speeds up `docker build` significantly. Test projects, CI config, docs, and IDE metadata are not needed in the production image.
733 -
734 - ```
735 - **/.git
736 - **/.vs
737 - **/.vscode
738 - **/.idea
739 - **/bin
740 - **/obj
741 - **/logs
742 - **/.DS_Store
743 - **/node_modules
744 - tests/
745 - .github/
746 - *.md
747 - .editorconfig
748 - .gitignore
749 - .env
750 - .env.example
751 - qodana.yaml
752 - compose.yml
753 - ```
754 -
755 - ### `.gitignore`
756 -
757 - The `.gitignore` file is a standard .NET template that excludes build output (`bin/`, `obj/`), IDE-specific directories (`.vs/`, `.idea/`, `.vscode/`), user-specific files (`*.user`, `launchSettings.json` overrides), and environment files (`.env`). It is ~300 lines and is generated via `dotnet new gitignore` — not reproduced here for brevity.
758 -
759 - ### `.env.example`
760 -
761 - Template for environment variables consumed by `compose.yml`. Developers copy this to `.env` and customize. The `.env` file is gitignored; this `.example` file is committed so new developers know what variables are needed.
762 -
763 - ```bash
764 - # ──────────────────────────────────────────────
765 - # Docker image
766 - # ──────────────────────────────────────────────
767 - DOCKER_IMAGE=your-dockerhub-username/{projects}-api
768 - IMAGE_TAG=latest
769 -
770 - # ──────────────────────────────────────────────
771 - # API configuration
772 - # ──────────────────────────────────────────────
773 - ASPNETCORE_ENVIRONMENT=Production
774 - API_PORT=5212
775 -
776 - # ──────────────────────────────────────────────
777 - # Database configuration
778 - # ──────────────────────────────────────────────
779 - POSTGRES_DB={projects}
780 - POSTGRES_USER=postgres
781 - POSTGRES_PASSWORD=change-me-to-a-strong-password
782 - DB_PORT=5432
783 -
784 - # ──────────────────────────────────────────────
785 - # Connection string (must match DB settings above)
786 - # ──────────────────────────────────────────────
787 - CONNECTION_STRING=Host=db;Port=5432;Database={projects};Username=postgres;Password=change-me-to-a-strong-password
788 - ```
789 -
790 - ### Install Packages into Projects
791 -
792 - With CPM, running `dotnet add package` registers the package in the `.csproj` (without a version). The version is resolved from `Directory.Packages.props`.
793 -
794 - ```bash
795 - # Application Layer
796 - dotnet add src/{ProjectName}.Application package MediatR
797 - dotnet add src/{ProjectName}.Application package FluentValidation
798 - dotnet add src/{ProjectName}.Application package FluentValidation.DependencyInjectionExtensions
799 - dotnet add src/{ProjectName}.Application package Microsoft.Extensions.Logging.Abstractions
800 -
801 - # Infrastructure Layer
802 - dotnet add src/{ProjectName}.Infrastructure package Microsoft.EntityFrameworkCore
803 - dotnet add src/{ProjectName}.Infrastructure package Microsoft.EntityFrameworkCore.Design
804 - dotnet add src/{ProjectName}.Infrastructure package Npgsql.EntityFrameworkCore.PostgreSQL
805 - dotnet add src/{ProjectName}.Infrastructure package Newtonsoft.Json
806 - dotnet add src/{ProjectName}.Infrastructure package Quartz.Extensions.Hosting
807 -
808 - # API Layer
809 - dotnet add src/{ProjectName}.Api package Serilog.AspNetCore
810 - dotnet add src/{ProjectName}.Api package Serilog.Enrichers.Environment
811 - dotnet add src/{ProjectName}.Api package Serilog.Enrichers.Thread
812 - dotnet add src/{ProjectName}.Api package AspNetCore.HealthChecks.NpgSql
813 - dotnet add src/{ProjectName}.Api package Microsoft.AspNetCore.OpenApi
814 - dotnet add src/{ProjectName}.Api package Microsoft.EntityFrameworkCore.Tools
815 - dotnet add src/{ProjectName}.Api package Asp.Versioning.Mvc
816 - dotnet add src/{ProjectName}.Api package Asp.Versioning.Mvc.ApiExplorer
817 -
818 - # Test Projects (Domain)
819 - dotnet add tests/{ProjectName}.Domain.Tests package Microsoft.NET.Test.Sdk
820 - dotnet add tests/{ProjectName}.Domain.Tests package xunit
821 - dotnet add tests/{ProjectName}.Domain.Tests package xunit.runner.visualstudio
822 - dotnet add tests/{ProjectName}.Domain.Tests package coverlet.collector
823 - dotnet add tests/{ProjectName}.Domain.Tests package FluentAssertions
824 - dotnet add tests/{ProjectName}.Domain.Tests package Moq
825 -
826 - # Test Projects (Application)
827 - dotnet add tests/{ProjectName}.Application.Tests package Microsoft.NET.Test.Sdk
828 - dotnet add tests/{ProjectName}.Application.Tests package xunit
829 - dotnet add tests/{ProjectName}.Application.Tests package xunit.runner.visualstudio
830 - dotnet add tests/{ProjectName}.Application.Tests package coverlet.collector
831 - dotnet add tests/{ProjectName}.Application.Tests package FluentAssertions
832 - dotnet add tests/{ProjectName}.Application.Tests package Moq
833 -
834 - # Test Projects (Integration)
835 - dotnet add tests/{ProjectName}.IntegrationTests package Microsoft.NET.Test.Sdk
836 - dotnet add tests/{ProjectName}.IntegrationTests package xunit
837 - dotnet add tests/{ProjectName}.IntegrationTests package xunit.runner.visualstudio
838 - dotnet add tests/{ProjectName}.IntegrationTests package coverlet.collector
839 - dotnet add tests/{ProjectName}.IntegrationTests package FluentAssertions
840 - dotnet add tests/{ProjectName}.IntegrationTests package Moq
841 - dotnet add tests/{ProjectName}.IntegrationTests package Microsoft.AspNetCore.Mvc.Testing
842 - ```
843 -
844 - ---
845 -
846 - ## 6. Project Files (.csproj)
847 -
848 - With CPM and `Directory.Build.props`, individual `.csproj` files are minimal. They declare only package references (no versions) and project references (enforcing the dependency rule).
849 -
850 - ### `src/{ProjectName}.Domain/{ProjectName}.Domain.csproj`
851 -
852 - The Domain project has **no NuGet dependencies at all**. This is intentional — the Domain layer must be pure C# with zero framework coupling.
853 -
854 - ```xml
855 - <Project Sdk="Microsoft.NET.Sdk">
856 -
857 - </Project>
858 - ```
859 -
860 - > Note: `TargetFramework`, `Nullable`, `ImplicitUsings`, and `TreatWarningsAsErrors` are inherited from `Directory.Build.props` — no need to repeat them.
861 -
862 - ### `src/{ProjectName}.Application/{ProjectName}.Application.csproj`
863 -
864 - References Domain and adds MediatR, FluentValidation, and logging abstractions.
865 -
866 - ```xml
867 - <Project Sdk="Microsoft.NET.Sdk">
868 -
869 - <ItemGroup>
870 - <ProjectReference Include="..\{Projects}.Domain\{Projects}.Domain.csproj"/>
871 - </ItemGroup>
872 -
873 - <ItemGroup>
874 - <PackageReference Include="FluentValidation"/>
875 - <PackageReference Include="FluentValidation.DependencyInjectionExtensions"/>
876 - <PackageReference Include="MediatR"/>
877 - <PackageReference Include="Microsoft.Extensions.Logging.Abstractions"/>
878 - </ItemGroup>
879 -
880 - </Project>
881 - ```
882 -
883 - ### `src/{ProjectName}.Infrastructure/{ProjectName}.Infrastructure.csproj`
884 -
885 - References Application and adds EF Core with PostgreSQL, Newtonsoft.Json, and Quartz for background jobs.
886 -
887 - ```xml
888 - <Project Sdk="Microsoft.NET.Sdk">
889 -
890 - <ItemGroup>
891 - <ProjectReference Include="..\{Projects}.Application\{Projects}.Application.csproj"/>
892 - </ItemGroup>
893 -
894 - <ItemGroup>
895 - <PackageReference Include="Microsoft.EntityFrameworkCore"/>
896 - <PackageReference Include="Microsoft.EntityFrameworkCore.Design">
897 - <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
898 - <PrivateAssets>all</PrivateAssets>
899 - </PackageReference>
900 - <PackageReference Include="Newtonsoft.Json"/>
901 - <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL"/>
902 - <PackageReference Include="Quartz.Extensions.Hosting"/>
903 - </ItemGroup>
904 -
905 - </Project>
906 - ```
907 -
908 - > `EF Core Design` is marked as a development-only dependency (`PrivateAssets: all`) — it's used by `dotnet ef` tooling at design time, not at runtime.
909 -
910 - ### `src/{ProjectName}.Api/{ProjectName}.Api.csproj`
911 -
912 - The web application project. Uses `Microsoft.NET.Sdk.Web` (not `Microsoft.NET.Sdk`). References both Application and Infrastructure to wire everything together at the composition root.
913 -
914 - ```xml
915 - <Project Sdk="Microsoft.NET.Sdk.Web">
916 -
917 - <ItemGroup>
918 - <PackageReference Include="Asp.Versioning.Mvc"/>
919 - <PackageReference Include="Asp.Versioning.Mvc.ApiExplorer"/>
920 - <PackageReference Include="AspNetCore.HealthChecks.NpgSql"/>
921 - <PackageReference Include="Microsoft.AspNetCore.OpenApi"/>
922 - <PackageReference Include="Microsoft.EntityFrameworkCore.Tools">
923 - <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
924 - <PrivateAssets>all</PrivateAssets>
925 - </PackageReference>
926 - <PackageReference Include="Serilog.AspNetCore"/>
927 - <PackageReference Include="Serilog.Enrichers.Environment"/>
928 - <PackageReference Include="Serilog.Enrichers.Thread"/>
929 - </ItemGroup>
930 -
931 - <ItemGroup>
932 - <ProjectReference Include="..\{Projects}.Application\{Projects}.Application.csproj"/>
933 - <ProjectReference Include="..\{Projects}.Infrastructure\{Projects}.Infrastructure.csproj"/>
934 - </ItemGroup>
935 -
936 - </Project>
937 - ```
938 -
939 - ### Test `.csproj` Files
940 -
941 - All test projects share the same structure: `IsPackable` set to `false` (prevents accidentally publishing test assemblies as NuGet packages), common test packages, a global `Using` for xUnit, and a single project reference to the layer under test.
942 -
943 - **`tests/{ProjectName}.Domain.Tests/{ProjectName}.Domain.Tests.csproj`**
944 - ```xml
945 - <Project Sdk="Microsoft.NET.Sdk">
946 -
947 - <PropertyGroup>
948 - <IsPackable>false</IsPackable>
949 - </PropertyGroup>
950 -
951 - <ItemGroup>
952 - <PackageReference Include="coverlet.collector"/>
953 - <PackageReference Include="FluentAssertions"/>
954 - <PackageReference Include="Microsoft.NET.Test.Sdk"/>
955 - <PackageReference Include="Moq"/>
956 - <PackageReference Include="xunit"/>
957 - <PackageReference Include="xunit.runner.visualstudio"/>
958 - </ItemGroup>
959 -
960 - <ItemGroup>
961 - <Using Include="Xunit"/>
962 - </ItemGroup>
963 -
964 - <ItemGroup>
965 - <ProjectReference Include="..\..\src\{Projects}.Domain\{Projects}.Domain.csproj"/>
966 - </ItemGroup>
967 -
968 - </Project>
969 - ```
970 -
971 - **`tests/{ProjectName}.Application.Tests/{ProjectName}.Application.Tests.csproj`**
972 - ```xml
973 - <Project Sdk="Microsoft.NET.Sdk">
974 -
975 - <PropertyGroup>
976 - <IsPackable>false</IsPackable>
977 - </PropertyGroup>
978 -
979 - <ItemGroup>
980 - <PackageReference Include="coverlet.collector"/>
981 - <PackageReference Include="FluentAssertions"/>
982 - <PackageReference Include="Microsoft.NET.Test.Sdk"/>
983 - <PackageReference Include="Moq"/>
984 - <PackageReference Include="xunit"/>
985 - <PackageReference Include="xunit.runner.visualstudio"/>
986 - </ItemGroup>
987 -
988 - <ItemGroup>
989 - <Using Include="Xunit"/>
990 - </ItemGroup>
991 -
992 - <ItemGroup>
993 - <ProjectReference Include="..\..\src\{Projects}.Application\{Projects}.Application.csproj"/>
994 - </ItemGroup>
995 -
996 - </Project>
997 - ```
998 -
999 - **`tests/{ProjectName}.IntegrationTests/{ProjectName}.IntegrationTests.csproj`**
1000 -
1001 - Integration tests reference the API project (which transitively brings in everything) and add `Microsoft.AspNetCore.Mvc.Testing` for `WebApplicationFactory<Program>` support.
1002 -
1003 - ```xml
1004 - <Project Sdk="Microsoft.NET.Sdk">
1005 -
1006 - <PropertyGroup>
1007 - <IsPackable>false</IsPackable>
1008 - </PropertyGroup>
1009 -
1010 - <ItemGroup>
1011 - <PackageReference Include="coverlet.collector"/>
1012 - <PackageReference Include="FluentAssertions"/>
1013 - <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing"/>
1014 - <PackageReference Include="Microsoft.NET.Test.Sdk"/>
1015 - <PackageReference Include="Moq"/>
1016 - <PackageReference Include="xunit"/>
1017 - <PackageReference Include="xunit.runner.visualstudio"/>
1018 - </ItemGroup>
1019 -
1020 - <ItemGroup>
1021 - <Using Include="Xunit"/>
1022 - </ItemGroup>
1023 -
1024 - <ItemGroup>
1025 - <ProjectReference Include="..\..\src\{Projects}.Api\{Projects}.Api.csproj"/>
1026 - </ItemGroup>
1027 -
1028 - </Project>
1029 - ```
1030 -
1031 - ---
1032 -
1033 - ## 7. Docker & Dev Environment
1034 -
1035 - ### `compose.yml` (Root)
1036 -
1037 - Sets up the API and a PostgreSQL database. All values are configurable via `.env` with sensible defaults for local development.
1038 -
1039 - ```yaml
1040 - services:
1041 - api:
1042 - container_name: {projects}-api
1043 - image: ${DOCKER_IMAGE:-{projects}-api}:${IMAGE_TAG:-latest}
1044 - build:
1045 - context: .
1046 - dockerfile: Dockerfile
1047 - ports:
1048 - - "${API_PORT:-5212}:8080"
1049 - environment:
1050 - - ASPNETCORE_ENVIRONMENT=${ASPNETCORE_ENVIRONMENT:-Development}
1051 - - ConnectionStrings__DefaultConnection=${CONNECTION_STRING:-Host=db;Port=5432;Database={projects}_dev;Username=postgres;Password=postgres}
1052 - depends_on:
1053 - db:
1054 - condition: service_healthy
1055 -
1056 - db:
1057 - container_name: {projects}-db
1058 - image: postgres:17-alpine
1059 - ports:
1060 - - "${DB_PORT:-5432}:5432"
1061 - environment:
1062 - POSTGRES_DB: ${POSTGRES_DB:-{projects}_dev}
1063 - POSTGRES_USER: ${POSTGRES_USER:-postgres}
1064 - POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
1065 - volumes:
1066 - - postgres_data:/var/lib/postgresql/data
1067 - healthcheck:
1068 - test: ["CMD-SHELL", "pg_isready -U postgres"]
1069 - interval: 5s
1070 - timeout: 5s
1071 - retries: 5
1072 -
1073 - volumes:
1074 - postgres_data:
1075 - ```
1076 -
1077 - ### `Dockerfile` (Root)
1078 -
1079 - Optimized multi-stage build. The key optimization is copying `.csproj` files first and running `dotnet restore` before copying source code — this means the NuGet restore layer is cached and only invalidated when dependencies change, not when code changes.
1080 -
1081 - ```dockerfile
1082 - FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base
1083 - WORKDIR /app
1084 - EXPOSE 8080
1085 -
1086 - FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
1087 - ARG BUILD_CONFIGURATION=Release
1088 - WORKDIR /src
1089 -
1090 - COPY global.json .
1091 - COPY nuget.config .
1092 - COPY Directory.Build.props .
1093 - COPY Directory.Packages.props .
1094 - COPY src/{Projects}.Api/{Projects}.Api.csproj src/{Projects}.Api/
1095 - COPY src/{Projects}.Application/{Projects}.Application.csproj src/{Projects}.Application/
1096 - COPY src/{Projects}.Domain/{Projects}.Domain.csproj src/{Projects}.Domain/
1097 - COPY src/{Projects}.Infrastructure/{Projects}.Infrastructure.csproj src/{Projects}.Infrastructure/
1098 -
1099 - RUN dotnet restore src/{Projects}.Api/{Projects}.Api.csproj
1100 -
1101 - COPY . .
1102 - RUN dotnet build src/{Projects}.Api -c $BUILD_CONFIGURATION --no-restore
1103 -
1104 - FROM build AS publish
1105 - ARG BUILD_CONFIGURATION=Release
1106 - RUN dotnet publish src/{Projects}.Api -c $BUILD_CONFIGURATION --no-build -o /app/publish /p:UseAppHost=false
1107 -
1108 - FROM base AS final
1109 - WORKDIR /app
1110 - COPY --from=publish /app/publish .
1111 - ENTRYPOINT ["dotnet", "{Projects}.Api.dll"]
1112 - ```
1113 -
1114 - ### `src/{ProjectName}.Api/Properties/launchSettings.json`
1115 -
1116 - Configures how `dotnet run` launches the API locally. Two profiles are defined: HTTP-only (port 5212) and HTTPS (ports 7031 + 5212). `launchBrowser` is disabled — APIs don't need a browser window.
1117 -
1118 - ```json
1119 - {
1120 - "$schema": "https://json.schemastore.org/launchsettings.json",
1121 - "profiles": {
1122 - "http": {
1123 - "commandName": "Project",
1124 - "dotnetRunMessages": true,
1125 - "launchBrowser": false,
1126 - "applicationUrl": "http://localhost:5212",
1127 - "environmentVariables": {
1128 - "ASPNETCORE_ENVIRONMENT": "Development"
1129 - }
1130 - },
1131 - "https": {
1132 - "commandName": "Project",
1133 - "dotnetRunMessages": true,
1134 - "launchBrowser": false,
1135 - "applicationUrl": "https://localhost:7031;http://localhost:5212",
1136 - "environmentVariables": {
1137 - "ASPNETCORE_ENVIRONMENT": "Development"
1138 - }
1139 - }
1140 - }
1141 - }
1142 - ```
1143 -
1144 - ---
1145 -
1146 - ## 8. Layer 1: Domain
1147 -
1148 - *The innermost layer. Contains entities, value objects, domain events, the Result pattern, and repository abstractions. It has **zero** NuGet dependencies — pure C# only.*
1149 -
1150 - **Why a dependency-free Domain?** The Domain layer encodes business rules. By keeping it free of frameworks (no EF Core attributes, no MediatR, no JSON serializers), it remains:
1151 - - Testable with plain unit tests (no mocking infrastructure).
1152 - - Portable — you can swap EF Core for Dapper or PostgreSQL for MongoDB without touching a single Domain file.
1153 - - Focused — developers reading Domain code see only business logic, not framework ceremony.
1154 -
1155 - ### `src/{ProjectName}.Domain/Common/BaseEntity.cs`
1156 -
1157 - All entities inherit from this. It provides a GUID primary key and a domain events collection. Domain events are raised by entities during business operations and dispatched after `SaveChanges` by the `DomainEventInterceptor` in the Infrastructure layer.
1158 -
1159 - ```csharp
1160 - namespace {Projects}.Domain.Common;
1161 -
1162 - public abstract class BaseEntity
1163 - {
1164 - private readonly List<IDomainEvent> _domainEvents = [];
1165 - public Guid Id { get; private init; } = Guid.NewGuid();
1166 - public IReadOnlyCollection<IDomainEvent> DomainEvents => _domainEvents.AsReadOnly();
1167 -
1168 - public void AddDomainEvent(IDomainEvent domainEvent) => _domainEvents.Add(domainEvent);
1169 - public void RemoveDomainEvent(IDomainEvent domainEvent) => _domainEvents.Remove(domainEvent);
1170 - public void ClearDomainEvents() => _domainEvents.Clear();
1171 - }
1172 - ```
1173 -
1174 - ### `src/{ProjectName}.Domain/Common/AuditableEntity.cs`
1175 -
1176 - Extends `BaseEntity` with `CreatedAt` and `UpdatedAt` timestamps. The setters are accessed by the `AuditableEntityInterceptor` — entities themselves don't need to worry about setting timestamps.
1177 -
1178 - ```csharp
1179 - namespace {Projects}.Domain.Common;
1180 -
1181 - public abstract class AuditableEntity : BaseEntity
1182 - {
1183 - public DateTime CreatedAt { get; private set; }
1184 - public DateTime? UpdatedAt { get; private set; }
1185 -
1186 - public void SetCreatedAt(DateTime createdAt) => CreatedAt = createdAt;
1187 - public void SetUpdatedAt(DateTime updatedAt) => UpdatedAt = updatedAt;
1188 - }
1189 - ```
1190 -
1191 - ### `src/{ProjectName}.Domain/Common/IDomainEvent.cs`
1192 -
1193 - Marker interface for domain events. Events carry a timestamp so consumers know when the event occurred.
1194 -
1195 - ```csharp
1196 - namespace {Projects}.Domain.Common;
1197 -
1198 - public interface IDomainEvent
1199 - {
1200 - DateTime OccurredOn { get; }
1201 - }
1202 - ```
1203 -
1204 - ### `src/{ProjectName}.Domain/Common/ValueObject.cs`
1205 -
1206 - Base class for value objects (DDD concept). Value objects are compared by their component values, not by identity. Two `Money(100, "USD")` instances are equal regardless of reference identity.
1207 -
1208 - ```csharp
1209 - namespace {Projects}.Domain.Common;
1210 -
1211 - public abstract class ValueObject : IEquatable<ValueObject>
1212 - {
1213 - protected abstract IEnumerable<object?> GetEqualityComponents();
1214 -
1215 - public override bool Equals(object? obj)
1216 - {
1217 - if (obj is null || obj.GetType() != GetType()) return false;
1218 - return Equals((ValueObject)obj);
1219 - }
1220 -
1221 - public bool Equals(ValueObject? other)
1222 - {
1223 - if (other is null || other.GetType() != GetType()) return false;
1224 - return GetEqualityComponents().SequenceEqual(other.GetEqualityComponents());
1225 - }
1226 -
1227 - public override int GetHashCode() => GetEqualityComponents().Aggregate(0, (current, obj) => HashCode.Combine(current, obj?.GetHashCode() ?? 0));
1228 - public static bool operator ==(ValueObject? left, ValueObject? right) => left is null && right is null || (left is not null && right is not null && left.Equals(right));
1229 - public static bool operator !=(ValueObject? left, ValueObject? right) => !(left == right);
1230 - }
1231 - ```
1232 -
1233 - ### `src/{ProjectName}.Domain/Common/Error.cs`
1234 -
1235 - Defines the `Error` record and `ErrorType` enum used throughout the Result pattern. Pre-defined static errors cover the most common failure cases. Domain-specific errors are defined alongside their entities (e.g., `User.Errors.EmailTaken`).
1236 -
1237 - ```csharp
1238 - namespace {Projects}.Domain.Common;
1239 -
1240 - public enum ErrorType { None = 0, Failure = 1, Validation = 2, NotFound = 3, Conflict = 4 }
1241 -
1242 - public sealed record Error(string Code, string Description, ErrorType Type)
1243 - {
1244 - public static readonly Error None = new(string.Empty, string.Empty, ErrorType.None);
1245 - public static readonly Error NullValue = new("Error.NullValue", "A null value was provided.", ErrorType.Failure);
1246 - public static readonly Error NotFound = new("Error.NotFound", "The requested resource was not found.", ErrorType.NotFound);
1247 - public static readonly Error Conflict = new("Error.Conflict", "A conflict occurred with the current state.", ErrorType.Conflict);
1248 - public static readonly Error Validation = new("Error.Validation", "A validation error occurred.", ErrorType.Validation);
1249 - }
1250 - ```
1251 -
1252 - ### `src/{ProjectName}.Domain/Common/Result.cs`
1253 -
1254 - The Result pattern implementation. Key design points:
1255 - - `IValidationResult` uses **static abstract interface members** (C# 13) — this enables `ValidationBehavior` to call `TResponse.Failure(error)` without reflection or `Activator.CreateInstance`.
1256 - - Constructor guards prevent invalid states (success with error, failure without error).
1257 - - `Result<T>` provides an implicit conversion from `T` for ergonomic returns.
1258 -
1259 - ```csharp
1260 - namespace {Projects}.Domain.Common;
1261 -
1262 - /// <summary>
1263 - /// Defines a contract for creating a failure result of a specific type.
1264 - /// Used for type-safe, high-performance validation in CQRS pipelines.
1265 - /// </summary>
1266 - public interface IValidationResult
1267 - {
1268 - static abstract Result Failure(Error error);
1269 - }
1270 -
1271 - public class Result : IValidationResult
1272 - {
1273 - protected Result(bool isSuccess, Error error)
1274 - {
1275 - if (isSuccess && error != Error.None)
1276 - throw new InvalidOperationException("A successful result cannot have an error.");
1277 -
1278 - if (!isSuccess && error == Error.None)
1279 - throw new InvalidOperationException("A failed result must have an error.");
1280 -
1281 - IsSuccess = isSuccess;
1282 - Error = error;
1283 - }
1284 -
1285 - public bool IsSuccess { get; }
1286 - public bool IsFailure => !IsSuccess;
1287 - public Error Error { get; }
1288 -
1289 - public static Result Success()
1290 - {
1291 - return new Result(true, Error.None);
1292 - }
1293 -
1294 - public static Result<T> Success<T>(T value)
1295 - {
1296 - return Result<T>.Success(value);
1297 - }
1298 -
1299 - public static Result Failure(Error error)
1300 - {
1301 - return new Result(false, error);
1302 - }
1303 -
1304 - public static Result<T> Failure<T>(Error error)
1305 - {
1306 - return Result<T>.Failure(error);
1307 - }
1308 - }
1309 -
1310 - public class Result<T> : Result, IValidationResult
1311 - {
1312 - private readonly T? _value;
1313 -
1314 - private Result(T? value, bool isSuccess, Error error)
1315 - : base(isSuccess, error)
1316 - {
1317 - _value = value;
1318 - }
1319 -
1320 - public T Value => IsSuccess
1321 - ? _value!
1322 - : throw new InvalidOperationException("Cannot access the value of a failed result.");
1323 -
1324 - public static Result<T> Success(T value)
1325 - {
1326 - return new Result<T>(value, true, Error.None);
1327 - }
1328 -
1329 - public new static Result<T> Failure(Error error)
1330 - {
1331 - return new Result<T>(default, false, error);
1332 - }
1333 -
1334 - public static implicit operator Result<T>(T value)
1335 - {
1336 - return Success(value);
1337 - }
1338 - }
1339 - ```
1340 -
1341 - ### `src/{ProjectName}.Domain/Abstractions/IUnitOfWork.cs`
1342 -
1343 - Abstracts the "save all pending changes" operation. In the Infrastructure layer, `ApplicationDbContext` implements this interface directly.
1344 -
1345 - ```csharp
1346 - namespace {Projects}.Domain.Abstractions;
1347 -
1348 - public interface IUnitOfWork
1349 - {
1350 - Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
1351 - }
1352 - ```
1353 -
1354 - ---
1355 -
1356 - ## 9. Layer 2: Application
1357 -
1358 - *Contains use cases (commands, queries, handlers), validation, mapping, and MediatR pipeline behaviors. References Domain only.*
1359 -
1360 - **Why a separate Application layer?** The Application layer orchestrates business operations without knowing *how* data is persisted or *how* HTTP requests arrive. This means:
1361 - - Handlers are testable by mocking `ApplicationDbContext` and `IUnitOfWork` — no database needed.
1362 - - The same handlers can serve a REST API, gRPC service, or message queue consumer.
1363 - - Validation is co-located with the command/query it validates.
1364 -
1365 - ### Messaging Interfaces (`src/{ProjectName}.Application/Abstractions/Messaging/`)
1366 -
1367 - These interfaces wrap MediatR's `IRequest` and `IRequestHandler` to enforce that all commands and queries return `Result` or `Result<T>`. This guarantees the Result pattern is used consistently throughout the application.
1368 -
1369 - **`ICommand.cs`**
1370 - ```csharp
1371 - using MediatR;
1372 - using {Projects}.Domain.Common;
1373 -
1374 - namespace {Projects}.Application.Abstractions.Messaging;
1375 -
1376 - /// <summary>
1377 - /// Marker interface for commands that do not return a value.
1378 - /// </summary>
1379 - public interface ICommand : IRequest<Result>;
1380 -
1381 - /// <summary>
1382 - /// Marker interface for commands that return a value wrapped in Result.
1383 - /// </summary>
1384 - public interface ICommand<TResponse> : IRequest<Result<TResponse>>;
1385 - ```
1386 -
1387 - **`ICommandHandler.cs`**
1388 - ```csharp
1389 - using MediatR;
1390 - using {Projects}.Domain.Common;
1391 -
1392 - namespace {Projects}.Application.Abstractions.Messaging;
1393 -
1394 - /// <summary>
1395 - /// Handler for commands that do not return a value.
1396 - /// </summary>
1397 - public interface ICommandHandler<in TCommand> : IRequestHandler<TCommand, Result>
1398 - where TCommand : ICommand;
1399 -
1400 - /// <summary>
1401 - /// Handler for commands that return a value wrapped in Result.
1402 - /// </summary>
1403 - public interface ICommandHandler<in TCommand, TResponse> : IRequestHandler<TCommand, Result<TResponse>>
1404 - where TCommand : ICommand<TResponse>;
1405 - ```
1406 -
1407 - **`IQuery.cs`**
1408 - ```csharp
1409 - using MediatR;
1410 - using {Projects}.Domain.Common;
1411 -
1412 - namespace {Projects}.Application.Abstractions.Messaging;
1413 -
1414 - /// <summary>
1415 - /// Marker interface for queries that return a value wrapped in Result.
1416 - /// </summary>
1417 - public interface IQuery<TResponse> : IRequest<Result<TResponse>>;
1418 - ```
1419 -
1420 - **`IQueryHandler.cs`**
1421 - ```csharp
1422 - using MediatR;
1423 - using {Projects}.Domain.Common;
1424 -
1425 - namespace {Projects}.Application.Abstractions.Messaging;
1426 -
1427 - /// <summary>
1428 - /// Handler for queries that return a value wrapped in Result.
1429 - /// </summary>
1430 - public interface IQueryHandler<in TQuery, TResponse> : IRequestHandler<TQuery, Result<TResponse>>
1431 - where TQuery : IQuery<TResponse>;
1432 - ```
1433 -
1434 - ### Domain Event Handler (`src/{ProjectName}.Application/Abstractions/IDomainEventHandler.cs`)
1435 -
1436 - Bridges domain events to MediatR's notification pipeline. `DomainEventNotification<T>` wraps any `IDomainEvent` as an `INotification`, keeping the Domain layer free of MediatR references.
1437 -
1438 - ```csharp
1439 - using MediatR;
1440 - using {Projects}.Domain.Common;
1441 -
1442 - namespace {Projects}.Application.Abstractions;
1443 -
1444 - /// <summary>
1445 - /// Wraps a domain event as a MediatR notification so it can be published
1446 - /// through the MediatR pipeline without coupling the Domain layer to MediatR.
1447 - /// </summary>
1448 - public sealed class DomainEventNotification<TDomainEvent>(TDomainEvent domainEvent)
1449 - : INotification where TDomainEvent : IDomainEvent
1450 - {
1451 - public TDomainEvent DomainEvent { get; } = domainEvent;
1452 - }
1453 -
1454 - /// <summary>
1455 - /// Convenience interface for handling domain events via MediatR.
1456 - /// Implement this instead of INotificationHandler&lt;DomainEventNotification&lt;T&gt;&gt; directly.
1457 - /// </summary>
1458 - public interface IDomainEventHandler<TDomainEvent>
1459 - : INotificationHandler<DomainEventNotification<TDomainEvent>>
1460 - where TDomainEvent : IDomainEvent;
1461 - ```
1462 -
1463 - ### Behaviors (`src/{ProjectName}.Application/Behaviors/`)
1464 -
1465 - Pipeline behaviors are MediatR middleware. They wrap every request and can inspect, modify, or short-circuit the pipeline.
1466 -
1467 - **`LoggingBehavior.cs`**
1468 -
1469 - Logs the request name before handling and the elapsed time after. Uses `Stopwatch` for high-resolution timing.
1470 -
1471 - ```csharp
1472 - using System.Diagnostics;
1473 - using MediatR;
1474 - using Microsoft.Extensions.Logging;
1475 -
1476 - namespace {Projects}.Application.Behaviors;
1477 -
1478 - public sealed class LoggingBehavior<TRequest, TResponse>(ILogger<LoggingBehavior<TRequest, TResponse>> logger) : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
1479 - {
1480 - public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
1481 - {
1482 - var requestName = typeof(TRequest).Name;
1483 - logger.LogInformation("Handling {RequestName}", requestName);
1484 - var stopwatch = Stopwatch.StartNew();
1485 - var response = await next(cancellationToken);
1486 - stopwatch.Stop();
1487 - logger.LogInformation("Handled {RequestName} in {ElapsedMilliseconds}ms", requestName, stopwatch.ElapsedMilliseconds);
1488 - return response;
1489 - }
1490 - }
1491 - ```
1492 -
1493 - **`ValidationBehavior.cs`** *(Zero Reflection / High-Performance)*
1494 -
1495 - Runs all registered `IValidator<TRequest>` validators before the handler executes. If any validation fails, it short-circuits the pipeline and returns a `Result.Failure` — the handler is never invoked.
1496 -
1497 - The key innovation is the `where TResponse : Result, IValidationResult` constraint combined with the `static abstract` method on `IValidationResult`. This allows `TResponse.Failure(error)` to be called directly — no reflection, no `Activator.CreateInstance`, fully AOT-compatible.
1498 -
1499 - ```csharp
1500 - using FluentValidation;
1501 - using MediatR;
1502 - using Microsoft.Extensions.Logging;
1503 - using {Projects}.Domain.Common;
1504 -
1505 - namespace {Projects}.Application.Behaviors;
1506 -
1507 - public sealed class ValidationBehavior<TRequest, TResponse>(
1508 - IEnumerable<IValidator<TRequest>> validators,
1509 - ILogger<ValidationBehavior<TRequest, TResponse>> logger)
1510 - : IPipelineBehavior<TRequest, TResponse>
1511 - where TRequest : IRequest<TResponse>
1512 - where TResponse : Result, IValidationResult
1513 - {
1514 - public async Task<TResponse> Handle(
1515 - TRequest request,
1516 - RequestHandlerDelegate<TResponse> next,
1517 - CancellationToken cancellationToken)
1518 - {
1519 - var validatorList = validators as IReadOnlyList<IValidator<TRequest>> ?? [.. validators];
1520 -
1521 - if (validatorList.Count == 0)
1522 - return await next(cancellationToken);
1523 -
1524 - var context = new ValidationContext<TRequest>(request);
1525 -
1526 - var validationResults = await Task.WhenAll(
1527 - validatorList.Select(v => v.ValidateAsync(context, cancellationToken)));
1528 -
1529 - var failures = validationResults
1530 - .SelectMany(r => r.Errors)
1531 - .Where(f => f is not null)
1532 - .ToList();
1533 -
1534 - if (failures.Count != 0)
1535 - {
1536 - var errorMessage = string.Join("; ", failures.Select(f => f.ErrorMessage));
1537 - var error = new Error("Validation", errorMessage, ErrorType.Validation);
1538 -
1539 - logger.LogWarning(
1540 - "Validation failed for {RequestName}: {ErrorMessage}",
1541 - typeof(TRequest).Name,
1542 - errorMessage);
1543 -
1544 - // Directly call the static abstract Failure method.
1545 - // No reflection, 100% type-safe and high performance.
1546 - return (TResponse)TResponse.Failure(error);
1547 - }
1548 -
1549 - return await next(cancellationToken);
1550 - }
1551 - }
1552 - ```
1553 -
1554 - ### Dependency Injection (`src/{ProjectName}.Application/DependencyInjection.cs`)
1555 -
1556 - Registers MediatR (with pipeline behaviors in order) and FluentValidation validators (auto-discovered from the assembly).
1557 -
1558 - ```csharp
1559 - using FluentValidation;
1560 - using MediatR;
1561 - using Microsoft.Extensions.DependencyInjection;
1562 - using {Projects}.Application.Behaviors;
1563 -
1564 - namespace {Projects}.Application;
1565 -
1566 - public static class DependencyInjection
1567 - {
1568 - public static IServiceCollection AddApplication(this IServiceCollection services)
1569 - {
1570 - var assembly = typeof(DependencyInjection).Assembly;
1571 -
1572 - services.AddMediatR(cfg =>
1573 - {
1574 - cfg.RegisterServicesFromAssembly(assembly);
1575 - cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));
1576 - cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
1577 - });
1578 -
1579 - services.AddValidatorsFromAssembly(assembly);
1580 -
1581 - return services;
1582 - }
1583 - }
1584 - ```
1585 -
1586 - ### Vertical Slice Convention
1587 -
1588 - > **Customize:** The folder structure below is a convention, not enforced by tooling. Adapt the nesting depth to your project's complexity.
1589 -
1590 - When adding features, organize the Application layer by **vertical slices** rather than by technical concern (no `Commands/`, `Queries/`, `Validators/` top-level folders). Each feature is a self-contained folder:
1591 -
1592 - ```
1593 - src/{ProjectName}.Application/
1594 - └── Features/
1595 - └── {FeatureName}/
1596 - ├── {Operation}/
1597 - │ ├── {Operation}Command.cs (or {Operation}Query.cs)
1598 - │ ├── {Operation}CommandHandler.cs (or {Operation}QueryHandler.cs)
1599 - │ ├── {Operation}CommandValidator.cs (optional)
1600 - │ └── {Operation}Response.cs (optional — only if returning data)
1601 - └── Mappings/
1602 - └── {FeatureName}Mappings.cs (static extension methods)
1603 - ```
1604 -
1605 - **Example for an "Items" feature:**
1606 -
1607 - ```
1608 - Features/
1609 - └── Items/
1610 - ├── CreateItem/
1611 - │ ├── CreateItemCommand.cs
1612 - │ ├── CreateItemCommandHandler.cs
1613 - │ └── CreateItemCommandValidator.cs
1614 - ├── GetItem/
1615 - │ ├── GetItemQuery.cs
1616 - │ ├── GetItemQueryHandler.cs
1617 - │ └── ItemResponse.cs
1618 - └── Mappings/
1619 - └── ItemMappings.cs
1620 - ```
1621 -
1622 - **Why vertical slices?**
1623 - - **Cohesion** — everything needed for a use case is in one folder; no jumping between `Commands/`, `Validators/`, `Handlers/`.
1624 - - **Discoverability** — new developers find related code immediately.
1625 - - **Safe deletion** — removing a feature means deleting one folder.
1626 - - **Reduced merge conflicts** — different developers working on different features rarely touch the same files.
1627 -
1628 - MediatR auto-discovers all `IRequestHandler<,>` and `IValidator<>` implementations from the assembly scan (configured in `DependencyInjection.cs`), so no manual registration is needed when adding new slices.
1629 -
1630 - ### Mapping Convention
1631 -
1632 - > **Customize:** If your project grows large enough to benefit from auto-mapping, you can introduce Mapster or AutoMapper later. Start with manual mapping.
1633 -
1634 - Use **static extension methods** for mapping between domain entities and response DTOs. Keep mapping logic close to the feature that uses it:
1635 -
1636 - ```csharp
1637 - // Features/Items/Mappings/ItemMappings.cs
1638 - namespace {Projects}.Application.Features.Items.Mappings;
1639 -
1640 - public static class ItemMappings
1641 - {
1642 - public static ItemResponse ToResponse(this Item entity) => new(
1643 - entity.Id,
1644 - entity.Name,
1645 - entity.CreatedAt);
1646 - }
1647 - ```
1648 -
1649 - **Why manual mapping over AutoMapper/Mapster?**
1650 - - **Zero magic** — mappings are plain C# code, fully debuggable with F12 / Go to Definition.
1651 - - **Compile-time safety** — missing properties cause build errors, not runtime surprises.
1652 - - **No hidden performance costs** — no reflection, no expression compilation, no global configuration scanning.
1653 - - **Co-located** — the mapping lives next to the feature that uses it.
1654 -
1655 - ### API Versioning Convention
1656 -
1657 - > **Customize:** The versioning strategy (URL path) is baked in. The version numbers and deprecation schedule are project-specific.
1658 -
1659 - Controllers use URL path versioning via `Asp.Versioning.Mvc`. Decorate controllers with `[ApiVersion]` and use `[Route("api/v{version:apiVersion}/[controller]")]`:
1660 -
1661 - ```csharp
1662 - using Asp.Versioning;
1663 -
1664 - [ApiVersion(1.0)]
1665 - [ApiController]
1666 - [Route("api/v{version:apiVersion}/[controller]")]
1667 - public class ItemsController : ControllerBase
1668 - {
1669 - // All endpoints in this controller are v1
1670 - // URL: /api/v1/items
1671 - }
1672 - ```
1673 -
1674 - When introducing breaking changes, add a new version:
1675 -
1676 - ```csharp
1677 - [ApiVersion(2.0)]
1678 - [ApiController]
1679 - [Route("api/v{version:apiVersion}/[controller]")]
1680 - public class ItemsV2Controller : ControllerBase
1681 - {
1682 - // URL: /api/v2/items
1683 - }
1684 - ```
1685 -
1686 - To deprecate an older version: `[ApiVersion(1.0, Deprecated = true)]`.
1687 -
1688 - ---
1689 -
1690 - ## 10. Layer 3: Infrastructure
1691 -
1692 - *Implements the abstractions defined in Domain and Application. Contains the EF Core `DbContext` and interceptors.*
1693 -
1694 - **Why Infrastructure is separate from Application:** The Application layer defines *what* operations are needed (via `IUnitOfWork` and feature-specific repository interfaces). Infrastructure provides *how* they're implemented (via EF Core, PostgreSQL, etc.). If you ever need to swap databases or add a caching layer, you change Infrastructure — Application and Domain remain untouched.
1695 -
1696 - ### Interceptors (`src/{ProjectName}.Infrastructure/Persistence/Interceptors/`)
1697 -
1698 - EF Core interceptors hook into the `SaveChanges` pipeline. They keep cross-cutting concerns out of the `DbContext` itself, making them individually testable and composable.
1699 -
1700 - **`AuditableEntityInterceptor.cs`**
1701 -
1702 - Automatically sets `CreatedAt` (on insert) and `UpdatedAt` (on update) for any entity that extends `AuditableEntity`. This means domain code never needs to manually set timestamps.
1703 -
1704 - ```csharp
1705 - using Microsoft.EntityFrameworkCore;
1706 - using Microsoft.EntityFrameworkCore.Diagnostics;
1707 - using {Projects}.Domain.Common;
1708 -
1709 - namespace {Projects}.Infrastructure.Persistence.Interceptors;
1710 -
1711 - public sealed class AuditableEntityInterceptor : SaveChangesInterceptor
1712 - {
1713 - public override ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
1714 - {
1715 - UpdateAuditableEntities(eventData.Context);
1716 - return base.SavingChangesAsync(eventData, result, cancellationToken);
1717 - }
1718 -
1719 - private static void UpdateAuditableEntities(DbContext? context)
1720 - {
1721 - if (context is null) return;
1722 - var utcNow = DateTime.UtcNow;
1723 - foreach (var entry in context.ChangeTracker.Entries<AuditableEntity>())
1724 - {
1725 - if (entry.State == EntityState.Added) entry.Entity.SetCreatedAt(utcNow);
1726 - if (entry.State == EntityState.Modified) entry.Entity.SetUpdatedAt(utcNow);
1727 - }
1728 - }
1729 - }
1730 - ```
1731 -
1732 - **`DomainEventInterceptor.cs`**
1733 -
1734 - Dispatches domain events **after** `SaveChanges` completes successfully. This ensures events are only published when the database transaction has committed. Events are collected from all tracked entities, the entity event lists are cleared, and each event is published through MediatR as a `DomainEventNotification<T>`.
1735 -
1736 - ```csharp
1737 - using MediatR;
1738 - using Microsoft.EntityFrameworkCore;
1739 - using Microsoft.EntityFrameworkCore.Diagnostics;
1740 - using {Projects}.Application.Abstractions;
1741 - using {Projects}.Domain.Common;
1742 -
1743 - namespace {Projects}.Infrastructure.Persistence.Interceptors;
1744 -
1745 - public sealed class DomainEventInterceptor(IPublisher publisher) : SaveChangesInterceptor
1746 - {
1747 - public override async ValueTask<int> SavedChangesAsync(SaveChangesCompletedEventData eventData, int result, CancellationToken cancellationToken = default)
1748 - {
1749 - if (eventData.Context is not null)
1750 - await PublishDomainEventsAsync(eventData.Context, cancellationToken);
1751 - return await base.SavedChangesAsync(eventData, result, cancellationToken);
1752 - }
1753 -
1754 - private async Task PublishDomainEventsAsync(DbContext context, CancellationToken cancellationToken)
1755 - {
1756 - var entities = context.ChangeTracker.Entries<BaseEntity>().Where(e => e.Entity.DomainEvents.Count != 0).Select(e => e.Entity).ToList();
1757 - var domainEvents = entities.SelectMany(e => e.DomainEvents).ToList();
1758 - entities.ForEach(e => e.ClearDomainEvents());
1759 -
1760 - foreach (var domainEvent in domainEvents)
1761 - {
1762 - var notificationType = typeof(DomainEventNotification<>).MakeGenericType(domainEvent.GetType());
1763 - var notification = Activator.CreateInstance(notificationType, domainEvent)!;
1764 - await publisher.Publish(notification, cancellationToken);
1765 - }
1766 - }
1767 - }
1768 - ```
1769 -
1770 - ### Database Context (`src/{ProjectName}.Infrastructure/Persistence/ApplicationDbContext.cs`)
1771 -
1772 - The EF Core `DbContext`. It also implements `IUnitOfWork` — calling `SaveChangesAsync` on the context fulfills the unit-of-work contract. Entity configurations are auto-discovered from the Infrastructure assembly via `ApplyConfigurationsFromAssembly`.
1773 -
1774 - ```csharp
1775 - using Microsoft.EntityFrameworkCore;
1776 - using {Projects}.Domain.Abstractions;
1777 -
1778 - namespace {Projects}.Infrastructure.Persistence;
1779 -
1780 - public sealed class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : DbContext(options), IUnitOfWork
1781 - {
1782 - protected override void OnModelCreating(ModelBuilder modelBuilder)
1783 - {
1784 - modelBuilder.ApplyConfigurationsFromAssembly(typeof(ApplicationDbContext).Assembly);
1785 - base.OnModelCreating(modelBuilder);
1786 - }
1787 - }
1788 - ```
1789 -
1790 - ### Dependency Injection (`src/{ProjectName}.Infrastructure/DependencyInjection.cs`)
1791 -
1792 - Registers the interceptors, `DbContext` (with PostgreSQL and interceptors wired in), and `IUnitOfWork`. Handlers access data directly through `ApplicationDbContext` — no generic repository abstraction. For complex data access patterns, create feature-specific repository interfaces in the Domain layer (e.g., `IMatchRepository`).
1793 -
1794 - ```csharp
1795 - using Microsoft.EntityFrameworkCore;
1796 - using Microsoft.Extensions.Configuration;
1797 - using Microsoft.Extensions.DependencyInjection;
1798 - using {Projects}.Domain.Abstractions;
1799 - using {Projects}.Infrastructure.Persistence;
1800 - using {Projects}.Infrastructure.Persistence.Interceptors;
1801 -
1802 - namespace {Projects}.Infrastructure;
1803 -
1804 - public static class DependencyInjection
1805 - {
1806 - public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
1807 - {
1808 - services.AddSingleton<AuditableEntityInterceptor>();
1809 - services.AddScoped<DomainEventInterceptor>();
1810 -
1811 - services.AddDbContext<ApplicationDbContext>((sp, options) =>
1812 - {
1813 - var auditableInterceptor = sp.GetRequiredService<AuditableEntityInterceptor>();
1814 - var domainEventInterceptor = sp.GetRequiredService<DomainEventInterceptor>();
1815 -
1816 - options.UseNpgsql(configuration.GetConnectionString("DefaultConnection"))
1817 - .AddInterceptors(auditableInterceptor, domainEventInterceptor);
1818 - });
1819 -
1820 - services.AddScoped<IUnitOfWork>(sp => sp.GetRequiredService<ApplicationDbContext>());
1821 -
1822 - return services;
1823 - }
1824 - }
1825 - ```
1826 -
1827 - > **Why `AuditableEntityInterceptor` is Singleton:** It has no mutable state and doesn't depend on scoped services — a single instance is reused across all requests, avoiding unnecessary allocations.
1828 - >
1829 - > **Why `DomainEventInterceptor` is Scoped:** It depends on `IPublisher` (MediatR), which is scoped to the HTTP request. Using a scoped lifetime ensures events are published through the correct scope.
1830 -
1831 - ---
1832 -
1833 - ## 11. Layer 4: API / Presentation
1834 -
1835 - *The outermost layer. Contains the ASP.NET Core web host, middleware, configuration, and the composition root where all layers are wired together.*
1836 -
1837 - **Why the API layer exists separately:** It is the composition root — the only place where all layers meet. Controllers receive HTTP requests, translate them into MediatR commands/queries, and map results back to HTTP responses. By keeping this layer thin, you ensure that business logic stays in Application and domain rules stay in Domain.
1838 -
1839 - ### `src/{ProjectName}.Api/appsettings.json`
1840 -
1841 - Main configuration file. Defines the connection string placeholder, Serilog configuration (structured console and file output with correlation ID, daily rolling log files), request logging options, and allowed hosts.
1842 -
1843 - ```json
1844 - {
1845 - "ConnectionStrings": {
1846 - "DefaultConnection": ""
1847 - },
1848 - "Serilog": {
1849 - "Using": ["Serilog.Sinks.Console", "Serilog.Sinks.File"],
1850 - "MinimumLevel": {
1851 - "Default": "Information",
1852 - "Override": { "Microsoft.AspNetCore": "Warning", "Microsoft.EntityFrameworkCore": "Warning" }
1853 - },
1854 - "WriteTo": [
1855 - { "Name": "Console", "Args": { "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext}{CorrelationId: [{CorrelationId}]} {Message:lj}{NewLine}{Exception}" } },
1856 - { "Name": "File", "Args": { "path": "logs/log-.txt", "rollingInterval": "Day", "retainedFileCountLimit": 7, "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {Level:u3}] {SourceContext}{CorrelationId: [{CorrelationId}]} {Message:lj}{NewLine}{Exception}" } }
1857 - ],
1858 - "Enrich": ["FromLogContext", "WithMachineName", "WithThreadId"]
1859 - },
1860 - "RequestLogging": {
1861 - "MaxBodySizeBytes": 65536,
1862 - "SlowRequestThresholdMs": 500,
1863 - "CorrelationIdHeader": "X-Correlation-Id",
1864 - "SensitiveFields": ["password", "token", "secret", "authorization", "creditCard", "ssn", "accessToken", "refreshToken"],
1865 - "LoggableContentTypes": ["application/json"],
1866 - "EnableRequestBodyLogging": true,
1867 - "EnableResponseBodyLogging": true,
1868 - "ExcludedPaths": ["/health"]
1869 - },
1870 - "AllowedHosts": "*"
1871 - }
1872 - ```
1873 -
1874 - ### `src/{ProjectName}.Api/appsettings.Development.json`
1875 -
1876 - Development overrides. Lowers the minimum log level to `Debug` for richer output during development, raises the slow request threshold to avoid noise, and provides a local PostgreSQL connection string.
1877 -
1878 - ```json
1879 - {
1880 - "ConnectionStrings": {
1881 - "DefaultConnection": "Host=localhost;Port=5432;Database={projects}_dev;Username=postgres;Password=postgres"
1882 - },
1883 - "Serilog": {
1884 - "MinimumLevel": {
1885 - "Default": "Debug",
1886 - "Override": {
1887 - "Microsoft.AspNetCore": "Information",
1888 - "Microsoft.EntityFrameworkCore": "Information"
1889 - }
1890 - }
1891 - },
1892 - "RequestLogging": {
1893 - "SlowRequestThresholdMs": 1000
1894 - }
1895 - }
1896 - ```
1897 -
1898 - ### `src/{ProjectName}.Api/Configuration/RequestLoggingOptions.cs`
1899 -
1900 - Strongly-typed options class for the request logging middleware. Bound from the `RequestLogging` section of `appsettings.json` via `IOptions<RequestLoggingOptions>`. All values have sensible defaults so the middleware works out of the box even without explicit configuration.
1901 -
1902 - ```csharp
1903 - namespace {Projects}.Api.Configuration;
1904 -
1905 - public sealed class RequestLoggingOptions
1906 - {
1907 - public const string SectionName = "RequestLogging";
1908 -
1909 - /// <summary>
1910 - /// Maximum request/response body size (in bytes) to capture in logs.
1911 - /// Bodies exceeding this limit are truncated. Default: 65,536 (64 KB).
1912 - /// </summary>
1913 - public int MaxBodySizeBytes { get; set; } = 65_536;
1914 -
1915 - /// <summary>
1916 - /// Requests exceeding this duration (in milliseconds) are logged at Warning level.
1917 - /// Default: 500ms.
1918 - /// </summary>
1919 - public int SlowRequestThresholdMs { get; set; } = 500;
1920 -
1921 - /// <summary>
1922 - /// The HTTP header name used for correlation ID propagation.
1923 - /// If the header is present on the incoming request, its value is reused;
1924 - /// otherwise a new GUID is generated. The correlation ID is always returned
1925 - /// in the response headers.
1926 - /// </summary>
1927 - public string CorrelationIdHeader { get; set; } = "X-Correlation-Id";
1928 -
1929 - /// <summary>
1930 - /// JSON field names whose values should be replaced with a redaction placeholder
1931 - /// before logging request/response bodies. Matching is case-insensitive.
1932 - /// </summary>
1933 - public List<string> SensitiveFields { get; set; } =
1934 - [
1935 - "password",
1936 - "token",
1937 - "secret",
1938 - "authorization",
1939 - "creditCard",
1940 - "ssn",
1941 - "accessToken",
1942 - "refreshToken"
1943 - ];
1944 -
1945 - /// <summary>
1946 - /// Content types for which request/response body logging is enabled.
1947 - /// Only JSON content types are included by default because
1948 - /// <see cref="SensitiveDataRedactor"/> only redacts JSON payloads.
1949 - /// Adding non-JSON types (XML, plain text) will cause sensitive data in
1950 - /// those formats to be logged unredacted.
1951 - /// </summary>
1952 - public List<string> LoggableContentTypes { get; set; } =
1953 - [
1954 - "application/json"
1955 - ];
1956 -
1957 - /// <summary>
1958 - /// When true, request bodies are captured and logged.
1959 - /// </summary>
1960 - public bool EnableRequestBodyLogging { get; set; } = true;
1961 -
1962 - /// <summary>
1963 - /// When true, response bodies are captured and logged.
1964 - /// </summary>
1965 - public bool EnableResponseBodyLogging { get; set; } = true;
1966 -
1967 - /// <summary>
1968 - /// Request paths that should be excluded from logging entirely.
1969 - /// Useful for high-frequency endpoints like health checks and readiness probes
1970 - /// that would otherwise generate excessive log noise.
1971 - /// </summary>
1972 - public List<string> ExcludedPaths { get; set; } =
1973 - [
1974 - "/health"
1975 - ];
1976 - }
1977 - ```
1978 -
1979 - ### `src/{ProjectName}.Api/Middleware/SensitiveDataRedactor.cs`
1980 -
1981 - Redacts sensitive field values from JSON content before it reaches the logs. This prevents passwords, tokens, and PII from being stored in log aggregation systems.
1982 -
1983 - **Dual-strategy approach:**
1984 - 1. **JSON DOM path** — for valid JSON, parses the content into a `JsonNode` tree and recursively replaces sensitive field values with `***REDACTED***`. This handles nested objects and arrays reliably.
1985 - 2. **Regex fallback** — for invalid/truncated JSON (e.g., bodies that exceeded `MaxBodySizeBytes`), uses a pre-compiled regex that matches `"sensitiveField": "value"` patterns. The regex has a 100ms timeout to prevent ReDoS attacks.
1986 -
1987 - ```csharp
1988 - using System.Text.Json;
1989 - using System.Text.Json.Nodes;
1990 - using System.Text.RegularExpressions;
1991 - using Microsoft.Extensions.Logging;
1992 - using Microsoft.Extensions.Options;
1993 - using {Projects}.Api.Configuration;
1994 -
1995 - namespace {Projects}.Api.Middleware;
1996 -
1997 - /// <summary>
1998 - /// Redacts sensitive field values from content before it is written to logs.
1999 - /// Field names to redact are configured via <see cref="RequestLoggingOptions.SensitiveFields"/>.
2000 - /// For valid JSON, uses a DOM-based approach for reliable recursive redaction.
2001 - /// For invalid/truncated JSON, falls back to regex-based pattern matching.
2002 - /// </summary>
2003 - public sealed class SensitiveDataRedactor
2004 - {
2005 - private const string RedactedPlaceholder = "***REDACTED***";
2006 -
2007 - private static readonly JsonSerializerOptions SerializerOptions = new() { WriteIndented = false };
2008 -
2009 - private readonly ILogger<SensitiveDataRedactor> _logger;
2010 - private readonly HashSet<string> _sensitiveFields;
2011 - private readonly Regex _fallbackRegex;
2012 -
2013 - public SensitiveDataRedactor(
2014 - ILogger<SensitiveDataRedactor> logger,
2015 - IOptions<RequestLoggingOptions> options)
2016 - {
2017 - _logger = logger;
2018 - _sensitiveFields = new HashSet<string>(
2019 - options.Value.SensitiveFields,
2020 - StringComparer.OrdinalIgnoreCase);
2021 -
2022 - // Build a regex that matches JSON key-value pairs for any sensitive field name.
2023 - // Pattern: "fieldName" : "..." — matches quoted string values only.
2024 - // Non-string values (numbers, booleans, null) are not matched by this regex;
2025 - // those are handled by the JSON DOM path for valid JSON.
2026 - if (_sensitiveFields.Count > 0)
2027 - {
2028 - var escapedFields = _sensitiveFields.Select(Regex.Escape);
2029 - var alternation = string.Join("|", escapedFields);
2030 -
2031 - var pattern = $"""
2032 - (?<="(?:{alternation})"\s*:\s*)"(?:[^"\\]|\\.)*"
2033 - """;
2034 -
2035 - _fallbackRegex = new Regex(
2036 - pattern.Trim(),
2037 - RegexOptions.IgnoreCase | RegexOptions.Compiled,
2038 - matchTimeout: TimeSpan.FromMilliseconds(100));
2039 - }
2040 - else
2041 - {
2042 - // No sensitive fields configured — use a regex that never matches.
2043 - _fallbackRegex = new Regex(
2044 - "(?!)",
2045 - RegexOptions.Compiled,
2046 - matchTimeout: TimeSpan.FromMilliseconds(100));
2047 - }
2048 - }
2049 -
2050 - /// <summary>
2051 - /// Redacts values of sensitive fields in the provided content.
2052 - /// Attempts JSON DOM-based redaction first. If the content is not valid JSON
2053 - /// (e.g. truncated bodies), falls back to regex-based pattern matching.
2054 - /// </summary>
2055 - public string Redact(string content)
2056 - {
2057 - if (string.IsNullOrWhiteSpace(content))
2058 - return content;
2059 -
2060 - try
2061 - {
2062 - var node = JsonNode.Parse(content);
2063 -
2064 - if (node is null)
2065 - return content;
2066 -
2067 - RedactNode(node);
2068 -
2069 - return node.ToJsonString(SerializerOptions);
2070 - }
2071 - catch (JsonException)
2072 - {
2073 - // Content is not valid JSON (e.g. truncated). Fall back to regex redaction.
2074 - return RedactWithRegex(content);
2075 - }
2076 - }
2077 -
2078 - /// <summary>
2079 - /// Regex-based fallback for redacting sensitive values in content that is not
2080 - /// parseable as JSON (e.g. truncated bodies). Replaces quoted string values
2081 - /// following sensitive field names with the redaction placeholder.
2082 - /// </summary>
2083 - private string RedactWithRegex(string content)
2084 - {
2085 - try
2086 - {
2087 - return _fallbackRegex.Replace(content, $"\"{RedactedPlaceholder}\"");
2088 - }
2089 - catch (RegexMatchTimeoutException)
2090 - {
2091 - _logger.LogWarning(
2092 - "Sensitive data redaction regex timed out — body redacted entirely to prevent sensitive data exposure");
2093 - return "[REDACTION FAILED — BODY SUPPRESSED]";
2094 - }
2095 - }
2096 -
2097 - private void RedactNode(JsonNode node)
2098 - {
2099 - switch (node)
2100 - {
2101 - case JsonObject jsonObject:
2102 - RedactObject(jsonObject);
2103 - break;
2104 -
2105 - case JsonArray jsonArray:
2106 - RedactArray(jsonArray);
2107 - break;
2108 - }
2109 - }
2110 -
2111 - private void RedactObject(JsonObject jsonObject)
2112 - {
2113 - var propertyNames = jsonObject.Select(p => p.Key).ToList();
2114 -
2115 - foreach (var name in propertyNames)
2116 - {
2117 - if (_sensitiveFields.Contains(name))
2118 - {
2119 - jsonObject[name] = RedactedPlaceholder;
2120 - continue;
2121 - }
2122 -
2123 - var child = jsonObject[name];
2124 -
2125 - if (child is not null)
2126 - RedactNode(child);
2127 - }
2128 - }
2129 -
2130 - private void RedactArray(JsonArray jsonArray)
2131 - {
2132 - foreach (var element in jsonArray)
2133 - {
2134 - if (element is not null)
2135 - RedactNode(element);
2136 - }
2137 - }
2138 - }
2139 - ```
2140 -
2141 - ### `src/{ProjectName}.Api/Middleware/RequestLoggingMiddleware.cs`
2142 -
2143 - Comprehensive HTTP request/response logging middleware. This is the largest single file in the boilerplate (~450 lines) because it handles many concerns carefully:
2144 -
2145 - - **Correlation ID tracking** — accepts a client-supplied correlation ID (validated for safety) or generates a new GUID. The ID is pushed into Serilog's `LogContext` so all downstream log entries include it.
2146 - - **Request/response body capture** — uses `EnableBuffering()` for the request stream and a `MemoryStream` swap for the response stream. Both are size-limited to `MaxBodySizeBytes`.
2147 - - **Sensitive data redaction** — bodies are passed through `SensitiveDataRedactor` before logging.
2148 - - **Slow request warnings** — requests exceeding `SlowRequestThresholdMs` trigger a warning-level log.
2149 - - **Path exclusion** — health checks and other high-frequency endpoints can be excluded to reduce log noise.
2150 - - **Security hardening** — correlation IDs are validated against a safe character set, client IPs are sanitized to prevent log injection, and UTF-8 truncation respects character boundaries.
2151 -
2152 - ```csharp
2153 - using System.Buffers;
2154 - using System.Diagnostics;
2155 - using System.Text;
2156 - using System.Text.RegularExpressions;
2157 - using Microsoft.Extensions.Options;
2158 - using Serilog.Context;
2159 - using {Projects}.Api.Configuration;
2160 -
2161 - namespace {Projects}.Api.Middleware;
2162 -
2163 - /// <summary>
2164 - /// Middleware that provides comprehensive HTTP request/response logging including:
2165 - /// <list type="bullet">
2166 - /// <item>Correlation ID tracking (accept from header or generate)</item>
2167 - /// <item>Request and response body capture (with configurable size limits)</item>
2168 - /// <item>Sensitive data redaction in logged bodies</item>
2169 - /// <item>Slow-request performance warnings</item>
2170 - /// <item>Enriched Serilog LogContext (client IP, user agent, user identity, etc.)</item>
2171 - /// </list>
2172 - /// </summary>
2173 - public sealed partial class RequestLoggingMiddleware
2174 - {
2175 - private const int MaxCorrelationIdLength = 128;
2176 -
2177 - private readonly RequestDelegate _next;
2178 - private readonly ILogger<RequestLoggingMiddleware> _logger;
2179 - private readonly RequestLoggingOptions _options;
2180 - private readonly SensitiveDataRedactor _redactor;
2181 - private readonly List<string> _excludedPathPrefixes;
2182 -
2183 - public RequestLoggingMiddleware(
2184 - RequestDelegate next,
2185 - ILogger<RequestLoggingMiddleware> logger,
2186 - IOptions<RequestLoggingOptions> options,
2187 - SensitiveDataRedactor redactor)
2188 - {
2189 - _next = next;
2190 - _logger = logger;
2191 - _options = options.Value;
2192 - _redactor = redactor;
2193 - _excludedPathPrefixes = _options.ExcludedPaths
2194 - .Select(p => p.TrimEnd('/'))
2195 - .ToList();
2196 - }
2197 -
2198 - public async Task InvokeAsync(HttpContext context)
2199 - {
2200 - // Skip logging for excluded paths (prefix match, e.g. /health also covers /health/ready).
2201 - var requestPath = context.Request.Path.ToString();
2202 -
2203 - if (IsExcludedPath(requestPath))
2204 - {
2205 - await _next(context);
2206 - return;
2207 - }
2208 -
2209 - var correlationId = GetOrCreateCorrelationId(context);
2210 - context.Items["CorrelationId"] = correlationId;
2211 - context.Response.OnStarting(() =>
2212 - {
2213 - context.Response.Headers[_options.CorrelationIdHeader] = correlationId;
2214 - return Task.CompletedTask;
2215 - });
2216 -
2217 - var clientIp = GetClientIp(context);
2218 - var userAgent = context.Request.Headers.UserAgent.ToString();
2219 -
2220 - // Push enrichment properties into Serilog's LogContext so that all
2221 - // downstream log entries within this request scope include them automatically.
2222 - using (LogContext.PushProperty("CorrelationId", correlationId))
2223 - using (LogContext.PushProperty("ClientIp", clientIp))
2224 - using (LogContext.PushProperty("UserAgent", userAgent))
2225 - using (LogContext.PushProperty("RequestMethod", context.Request.Method))
2226 - using (LogContext.PushProperty("RequestPath", requestPath))
2227 - using (LogContext.PushProperty("QueryString", context.Request.QueryString.ToString()))
2228 - using (LogContext.PushProperty("UserIdentity", context.User.Identity?.Name ?? "anonymous"))
2229 - {
2230 - var requestBody = await CaptureRequestBodyAsync(context);
2231 -
2232 - _logger.LogDebug(
2233 - "HTTP {RequestMethod} {RequestPath}{QueryString} started",
2234 - context.Request.Method,
2235 - context.Request.Path,
2236 - context.Request.QueryString);
2237 -
2238 - if (requestBody.Content.Length > 0)
2239 - {
2240 - _logger.LogDebug(
2241 - "Request body: {RequestBody}",
2242 - FormatBodyForLog(requestBody));
2243 - }
2244 -
2245 - // Only allocate and swap the response body stream when response body logging is enabled.
2246 - Stream? originalBodyStream = null;
2247 - MemoryStream? responseBodyStream = null;
2248 -
2249 - if (_options.EnableResponseBodyLogging)
2250 - {
2251 - originalBodyStream = context.Response.Body;
2252 - responseBodyStream = new MemoryStream();
2253 - context.Response.Body = responseBodyStream;
2254 - }
2255 -
2256 - // Start timing just before calling the next middleware so the elapsed time
2257 - // reflects actual pipeline processing, not request body capture overhead.
2258 - var stopwatch = Stopwatch.StartNew();
2259 -
2260 - try
2261 - {
2262 - await _next(context);
2263 - }
2264 - finally
2265 - {
2266 - stopwatch.Stop();
2267 - var elapsedMs = stopwatch.ElapsedMilliseconds;
2268 -
2269 - var responseBody = CapturedBody.Empty;
2270 -
2271 - if (_options.EnableResponseBodyLogging
2272 - && responseBodyStream is not null
2273 - && originalBodyStream is not null)
2274 - {
2275 - responseBody = await CaptureResponseBodySafeAsync(
2276 - context, responseBodyStream, originalBodyStream);
2277 - }
2278 -
2279 - _logger.LogInformation(
2280 - "HTTP {RequestMethod} {RequestPath} completed {StatusCode} in {ElapsedMs}ms",
2281 - context.Request.Method,
2282 - context.Request.Path,
2283 - context.Response.StatusCode,
2284 - elapsedMs);
2285 -
2286 - if (responseBody.Content.Length > 0)
2287 - {
2288 - _logger.LogDebug(
2289 - "Response body: {ResponseBody}",
2290 - FormatBodyForLog(responseBody));
2291 - }
2292 -
2293 - if (elapsedMs > _options.SlowRequestThresholdMs)
2294 - {
2295 - _logger.LogWarning(
2296 - "Slow request detected: HTTP {RequestMethod} {RequestPath} took {ElapsedMs}ms (threshold: {ThresholdMs}ms)",
2297 - context.Request.Method,
2298 - context.Request.Path,
2299 - elapsedMs,
2300 - _options.SlowRequestThresholdMs);
2301 - }
2302 -
2303 - if (responseBodyStream is not null)
2304 - await responseBodyStream.DisposeAsync();
2305 - }
2306 - }
2307 - }
2308 -
2309 - /// <summary>
2310 - /// Redacts the body content first, then appends the truncation marker if needed.
2311 - /// This ensures sensitive fields are redacted even in truncated bodies.
2312 - /// </summary>
2313 - private string FormatBodyForLog(CapturedBody body)
2314 - {
2315 - var redacted = _redactor.Redact(body.Content);
2316 -
2317 - return body.IsTruncated
2318 - ? $"{redacted} ... [TRUNCATED - body exceeds {_options.MaxBodySizeBytes} bytes]"
2319 - : redacted;
2320 - }
2321 -
2322 - private bool IsExcludedPath(string path)
2323 - {
2324 - foreach (var prefix in _excludedPathPrefixes)
2325 - {
2326 - if (path.Equals(prefix, StringComparison.OrdinalIgnoreCase)
2327 - || path.StartsWith(prefix + "/", StringComparison.OrdinalIgnoreCase))
2328 - {
2329 - return true;
2330 - }
2331 - }
2332 -
2333 - return false;
2334 - }
2335 -
2336 - private string GetOrCreateCorrelationId(HttpContext context)
2337 - {
2338 - if (context.Request.Headers.TryGetValue(_options.CorrelationIdHeader, out var existingId)
2339 - && !string.IsNullOrWhiteSpace(existingId))
2340 - {
2341 - var candidate = existingId.ToString();
2342 -
2343 - if (candidate.Length <= MaxCorrelationIdLength && SafeCorrelationIdRegex().IsMatch(candidate))
2344 - return candidate;
2345 -
2346 - // Invalid or oversized correlation ID from client; generate a new one.
2347 - }
2348 -
2349 - return Guid.NewGuid().ToString();
2350 - }
2351 -
2352 - private async Task<CapturedBody> CaptureRequestBodyAsync(HttpContext context)
2353 - {
2354 - if (!_options.EnableRequestBodyLogging)
2355 - return CapturedBody.Empty;
2356 -
2357 - if (!IsLoggableContentType(context.Request.ContentType))
2358 - return CapturedBody.Empty;
2359 -
2360 - context.Request.EnableBuffering();
2361 -
2362 - // Read the request body at the byte level. EnableBuffering() wraps the stream
2363 - // so it supports seeking, allowing us to reset the position after reading.
2364 - var body = await ReadStreamBytesAsync(context.Request.Body, _options.MaxBodySizeBytes);
2365 -
2366 - context.Request.Body.Position = 0;
2367 -
2368 - return body;
2369 - }
2370 -
2371 - /// <summary>
2372 - /// Captures the response body from the memory stream and copies it to the original
2373 - /// response stream. Wrapped in a try/catch so that a failure here (e.g. the response
2374 - /// has already started on the original stream) does not mask the original exception.
2375 - /// </summary>
2376 - private async Task<CapturedBody> CaptureResponseBodySafeAsync(
2377 - HttpContext context,
2378 - MemoryStream responseBodyStream,
2379 - Stream originalBodyStream)
2380 - {
2381 - try
2382 - {
2383 - responseBodyStream.Position = 0;
2384 -
2385 - var body = CapturedBody.Empty;
2386 -
2387 - if (IsLoggableContentType(context.Response.ContentType))
2388 - {
2389 - body = await ReadStreamFromMemoryAsync(responseBodyStream, _options.MaxBodySizeBytes);
2390 - }
2391 -
2392 - responseBodyStream.Position = 0;
2393 - await responseBodyStream.CopyToAsync(originalBodyStream);
2394 - context.Response.Body = originalBodyStream;
2395 -
2396 - return body;
2397 - }
2398 - catch (Exception ex)
2399 - {
2400 - _logger.LogDebug(ex, "Failed to capture response body for logging");
2401 -
2402 - // Best-effort: try to restore the original body stream so the client gets a response.
2403 - try
2404 - {
2405 - context.Response.Body = originalBodyStream;
2406 - }
2407 - catch
2408 - {
2409 - // Nothing more we can do.
2410 - }
2411 -
2412 - return CapturedBody.Empty;
2413 - }
2414 - }
2415 -
2416 - /// <summary>
2417 - /// Reads a stream at the byte level, suitable for forward-only streams (e.g. request body)
2418 - /// where <c>stream.Length</c> may not be available before the stream is consumed.
2419 - /// Uses <see cref="ArrayPool{T}"/> to avoid large object heap allocations.
2420 - /// The limit is enforced in bytes to match <c>MaxBodySizeBytes</c>.
2421 - /// Truncation respects UTF-8 character boundaries.
2422 - /// </summary>
2423 - private static async Task<CapturedBody> ReadStreamBytesAsync(Stream stream, int maxBytes)
2424 - {
2425 - stream.Position = 0;
2426 -
2427 - // Read one extra byte to detect whether the stream has more data beyond the limit.
2428 - var readLimit = maxBytes + 1;
2429 - var buffer = ArrayPool<byte>.Shared.Rent(readLimit);
2430 -
2431 - try
2432 - {
2433 - var totalRead = 0;
2434 -
2435 - while (totalRead < readLimit)
2436 - {
2437 - var bytesRead = await stream.ReadAsync(buffer.AsMemory(totalRead, readLimit - totalRead));
2438 -
2439 - if (bytesRead == 0)
2440 - break;
2441 -
2442 - totalRead += bytesRead;
2443 - }
2444 -
2445 - var isTruncated = totalRead > maxBytes;
2446 - var usableBytes = Math.Min(totalRead, maxBytes);
2447 -
2448 - // Adjust the truncation point to avoid splitting a multi-byte UTF-8 sequence.
2449 - if (isTruncated)
2450 - usableBytes = FindUtf8SafeTruncationPoint(buffer, usableBytes);
2451 -
2452 - var content = Encoding.UTF8.GetString(buffer, 0, usableBytes);
2453 -
2454 - return new CapturedBody(content, isTruncated);
2455 - }
2456 - finally
2457 - {
2458 - ArrayPool<byte>.Shared.Return(buffer);
2459 - }
2460 - }
2461 -
2462 - /// <summary>
2463 - /// Reads a MemoryStream where <c>stream.Length</c> is reliable.
2464 - /// Used for response body capture. Uses <see cref="ArrayPool{T}"/> to avoid
2465 - /// per-request heap allocations.
2466 - /// Truncation respects UTF-8 character boundaries.
2467 - /// </summary>
2468 - private static async Task<CapturedBody> ReadStreamFromMemoryAsync(MemoryStream stream, int maxBytes)
2469 - {
2470 - stream.Position = 0;
2471 -
2472 - var length = stream.Length;
2473 - var bytesToRead = (int)Math.Min(maxBytes, length);
2474 - var buffer = ArrayPool<byte>.Shared.Rent(bytesToRead);
2475 -
2476 - try
2477 - {
2478 - var bytesRead = await stream.ReadAsync(buffer.AsMemory(0, bytesToRead));
2479 -
2480 - var isTruncated = length > maxBytes;
2481 -
2482 - var usableBytes = bytesRead;
2483 -
2484 - // Adjust the truncation point to avoid splitting a multi-byte UTF-8 sequence.
2485 - if (isTruncated)
2486 - usableBytes = FindUtf8SafeTruncationPoint(buffer, bytesRead);
2487 -
2488 - var content = Encoding.UTF8.GetString(buffer, 0, usableBytes);
2489 -
2490 - return new CapturedBody(content, isTruncated);
2491 - }
2492 - finally
2493 - {
2494 - ArrayPool<byte>.Shared.Return(buffer);
2495 - }
2496 - }
2497 -
2498 - /// <summary>
2499 - /// Walks backwards from <paramref name="length"/> to find a byte position that
2500 - /// does not split a multi-byte UTF-8 character. UTF-8 continuation bytes have the
2501 - /// bit pattern <c>10xxxxxx</c> (0x80..0xBF). If the byte at the truncation point
2502 - /// is a continuation byte, we step back until we reach the leading byte of that
2503 - /// character and exclude the incomplete sequence.
2504 - /// </summary>
2505 - private static int FindUtf8SafeTruncationPoint(byte[] buffer, int length)
2506 - {
2507 - if (length == 0)
2508 - return 0;
2509 -
2510 - // Walk backwards over any continuation bytes (10xxxxxx).
2511 - var i = length - 1;
2512 - while (i > 0 && (buffer[i] & 0xC0) == 0x80)
2513 - i--;
2514 -
2515 - // i now points at a leading byte (or byte 0). Determine the expected
2516 - // character length from the leading byte.
2517 - var leadByte = buffer[i];
2518 - int expectedCharBytes;
2519 -
2520 - if ((leadByte & 0x80) == 0)
2521 - expectedCharBytes = 1; // 0xxxxxxx — ASCII
2522 - else if ((leadByte & 0xE0) == 0xC0)
2523 - expectedCharBytes = 2; // 110xxxxx
2524 - else if ((leadByte & 0xF0) == 0xE0)
2525 - expectedCharBytes = 3; // 1110xxxx
2526 - else if ((leadByte & 0xF8) == 0xF0)
2527 - expectedCharBytes = 4; // 11110xxx
2528 - else
2529 - return i; // Invalid leading byte — truncate before it.
2530 -
2531 - // If the full character fits within the buffer, keep it; otherwise drop it.
2532 - return i + expectedCharBytes <= length ? length : i;
2533 - }
2534 -
2535 - private bool IsLoggableContentType(string? contentType)
2536 - {
2537 - if (string.IsNullOrWhiteSpace(contentType))
2538 - return false;
2539 -
2540 - return _options.LoggableContentTypes.Exists(
2541 - ct => contentType.Contains(ct, StringComparison.OrdinalIgnoreCase));
2542 - }
2543 -
2544 - private static string GetClientIp(HttpContext context)
2545 - {
2546 - // Check for forwarded headers first (reverse proxy scenarios).
2547 - var forwardedFor = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
2548 -
2549 - if (!string.IsNullOrWhiteSpace(forwardedFor))
2550 - {
2551 - // X-Forwarded-For may contain multiple IPs; the first is the original client.
2552 - var ip = forwardedFor.Split(',', StringSplitOptions.TrimEntries)[0];
2553 - return SanitizeForLog(ip);
2554 - }
2555 -
2556 - return context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
2557 - }
2558 -
2559 - /// <summary>
2560 - /// Strips control characters and newlines from a string to prevent log injection.
2561 - /// Limits length to avoid unbounded values in log output.
2562 - /// </summary>
2563 - private static string SanitizeForLog(string value)
2564 - {
2565 - const int maxLength = 45; // Max length of an IPv6 address with zone ID
2566 -
2567 - if (value.Length > maxLength)
2568 - value = value[..maxLength];
2569 -
2570 - return LogSanitizeRegex().Replace(value, string.Empty);
2571 - }
2572 -
2573 - /// <summary>
2574 - /// Matches control characters, newlines, and other non-printable characters
2575 - /// that could be used for log injection.
2576 - /// </summary>
2577 - [GeneratedRegex(@"[\x00-\x1F\x7F]")]
2578 - private static partial Regex LogSanitizeRegex();
2579 -
2580 - /// <summary>
2581 - /// Matches safe correlation ID values: alphanumeric characters, hyphens, underscores,
2582 - /// periods, and colons. Rejects control characters, braces (Serilog template injection),
2583 - /// and other unsafe characters.
2584 - /// </summary>
2585 - [GeneratedRegex(@"^[\w\-.:]+$")]
2586 - private static partial Regex SafeCorrelationIdRegex();
2587 -
2588 - /// <summary>
2589 - /// Represents a captured request or response body along with a flag indicating
2590 - /// whether the body was truncated to fit within the configured size limit.
2591 - /// Separating the content from the truncation flag allows the redactor to operate
2592 - /// on valid (non-truncated) content before the truncation marker is appended.
2593 - /// </summary>
2594 - private readonly record struct CapturedBody(string Content, bool IsTruncated)
2595 - {
2596 - public static readonly CapturedBody Empty = new(string.Empty, false);
2597 - }
2598 - }
2599 - ```
2600 -
2601 - ### `src/{ProjectName}.Api/Middleware/GlobalExceptionHandler.cs`
2602 -
2603 - Catches all unhandled exceptions and returns a standardized `ProblemDetails` response. In development, the exception message is included for debugging; in production, a generic message is returned to avoid leaking internals.
2604 -
2605 - ```csharp
2606 - using System.Net;
2607 - using Microsoft.AspNetCore.Diagnostics;
2608 - using Microsoft.AspNetCore.Mvc;
2609 -
2610 - namespace {Projects}.Api.Middleware;
2611 -
2612 - public sealed class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
2613 - {
2614 - public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
2615 - {
2616 - logger.LogError(exception, "An unhandled exception occurred: {Message}", exception.Message);
2617 -
2618 - var problemDetails = new ProblemDetails
2619 - {
2620 - Status = (int)HttpStatusCode.InternalServerError,
2621 - Title = "An unexpected error occurred",
2622 - Detail = httpContext.RequestServices.GetRequiredService<IHostEnvironment>().IsDevelopment() ? exception.Message : "An internal server error has occurred.",
2623 - Instance = httpContext.Request.Path
2624 - };
2625 -
2626 - httpContext.Response.StatusCode = problemDetails.Status.Value;
2627 - httpContext.Response.ContentType = "application/problem+json";
2628 - await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken: cancellationToken);
2629 - return true;
2630 - }
2631 - }
2632 - ```
2633 -
2634 - ### `src/{ProjectName}.Api/Extensions/ServiceCollectionExtensions.cs`
2635 -
2636 - The composition root's service registration. Wires together:
2637 - - Serilog (reads config from `appsettings.json`)
2638 - - Request logging options and redactor
2639 - - Controllers, OpenAPI, exception handler, problem details
2640 - - API versioning (URL path segment: `/api/v1/`)
2641 - - Application layer (MediatR + behaviors + validators)
2642 - - Infrastructure layer (EF Core + interceptors)
2643 - - Health checks (PostgreSQL connectivity)
2644 -
2645 - ```csharp
2646 - using Asp.Versioning;
2647 - using Serilog;
2648 - using {Projects}.Api.Configuration;
2649 - using {Projects}.Api.Middleware;
2650 - using {Projects}.Application;
2651 - using {Projects}.Infrastructure;
2652 -
2653 - namespace {Projects}.Api.Extensions;
2654 -
2655 - public static class ServiceCollectionExtensions
2656 - {
2657 - public static WebApplicationBuilder AddServices(this WebApplicationBuilder builder)
2658 - {
2659 - builder.Host.UseSerilog((context, loggerConfiguration) =>
2660 - loggerConfiguration.ReadFrom.Configuration(context.Configuration));
2661 -
2662 - builder.Services.Configure<RequestLoggingOptions>(
2663 - builder.Configuration.GetSection(RequestLoggingOptions.SectionName));
2664 - builder.Services.AddSingleton<SensitiveDataRedactor>();
2665 -
2666 - builder.Services.AddControllers();
2667 - builder.Services.AddOpenApi();
2668 - builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
2669 - builder.Services.AddProblemDetails();
2670 -
2671 - builder.Services.AddApiVersioning(options =>
2672 - {
2673 - options.DefaultApiVersion = new ApiVersion(1, 0);
2674 - options.AssumeDefaultVersionWhenUnspecified = true;
2675 - options.ReportApiVersions = true;
2676 - options.ApiVersionReader = new UrlSegmentApiVersionReader();
2677 - })
2678 - .AddApiExplorer(options =>
2679 - {
2680 - options.GroupNameFormat = "'v'VVV";
2681 - options.SubstituteApiVersionInUrl = true;
2682 - });
2683 -
2684 - builder.Services.AddApplication();
2685 - builder.Services.AddInfrastructure(builder.Configuration);
2686 -
2687 - var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
2688 - ?? throw new InvalidOperationException(
2689 - "Connection string 'DefaultConnection' is not configured.");
2690 -
2691 - builder.Services.AddHealthChecks()
2692 - .AddNpgSql(connectionString);
2693 -
2694 - return builder;
2695 - }
2696 - }
2697 - ```
2698 -
2699 - ### `src/{ProjectName}.Api/Extensions/WebApplicationExtensions.cs`
2700 -
2701 - Configures the HTTP request pipeline (middleware order matters):
2702 - 1. OpenAPI endpoint (development only)
2703 - 2. `RequestLoggingMiddleware` — must come early to capture the full request lifecycle
2704 - 3. Exception handler — catches exceptions from downstream middleware
2705 - 4. HTTPS redirection
2706 - 5. Authorization
2707 - 6. Controller mapping
2708 - 7. Health check endpoint
2709 -
2710 - ```csharp
2711 - using {Projects}.Api.Middleware;
2712 -
2713 - namespace {Projects}.Api.Extensions;
2714 -
2715 - public static class WebApplicationExtensions
2716 - {
2717 - public static WebApplication ConfigurePipeline(this WebApplication app)
2718 - {
2719 - if (app.Environment.IsDevelopment())
2720 - app.MapOpenApi();
2721 -
2722 - app.UseMiddleware<RequestLoggingMiddleware>();
2723 - app.UseExceptionHandler();
2724 - app.UseHttpsRedirection();
2725 - app.UseAuthorization();
2726 - app.MapControllers();
2727 - app.MapHealthChecks("/health");
2728 -
2729 - return app;
2730 - }
2731 - }
2732 - ```
2733 -
2734 - ### `src/{ProjectName}.Api/Program.cs`
2735 -
2736 - The application entry point. Deliberately minimal — all setup is delegated to extension methods. The try/catch/finally ensures Serilog captures fatal startup errors and flushes all buffered log events on shutdown.
2737 -
2738 - The `public partial class Program;` declaration at the end enables `WebApplicationFactory<Program>` in integration tests.
2739 -
2740 - ```csharp
2741 - using Serilog;
2742 - using {Projects}.Api.Extensions;
2743 -
2744 - var builder = WebApplication.CreateBuilder(args);
2745 -
2746 - builder.AddServices();
2747 -
2748 - var app = builder.Build();
2749 -
2750 - app.ConfigurePipeline();
2751 -
2752 - try
2753 - {
2754 - Log.Information("Starting {Projects} API in {Environment} environment", app.Environment.EnvironmentName);
2755 - app.Run();
2756 - }
2757 - catch (Exception ex)
2758 - {
2759 - Log.Fatal(ex, "Application terminated unexpectedly");
2760 - }
2761 - finally
2762 - {
2763 - Log.CloseAndFlush();
2764 - }
2765 -
2766 - public partial class Program;
2767 - ```
2768 -
2769 - ---
2770 -
2771 - ## 12. Test Projects
1 + ## 10. Test Projects
2772 2
2773 3 ### Test Strategy
2774 4
@@ -2776,9 +6,9 @@ The boilerplate scaffolds three test projects, each targeting a different layer
2776 6
2777 7 | Project | Tests | Style |
2778 8 |---|---|---|
2779 - | `{ProjectName}.Domain.Tests` | Entities, value objects, Result pattern, domain logic | Pure unit tests — no mocks needed (Domain has zero dependencies) |
2780 - | `{ProjectName}.Application.Tests` | Command/query handlers, validators, pipeline behaviors | Unit tests with mocked `ApplicationDbContext` and `IUnitOfWork` |
2781 - | `{ProjectName}.IntegrationTests` | Full HTTP request/response cycle through the API | Integration tests using `WebApplicationFactory<Program>` with a real PostgreSQL instance |
9 + | `${PROJECT}.Domain.Tests` | Entities, value objects, Result pattern, domain logic | Pure unit tests — no mocks needed (Domain has zero dependencies) |
10 + | `${PROJECT}.Application.Tests` | Command/query handlers, validators, pipeline behaviors | Unit tests with mocked `ApplicationDbContext` and `IUnitOfWork` |
11 + | `${PROJECT}.IntegrationTests` | Full HTTP request/response cycle through the API | Integration tests using `WebApplicationFactory<Program>` with a real PostgreSQL instance |
2782 12
2783 13 **Shared test tooling across all projects:**
2784 14 - **xUnit** — test framework (`[Fact]`, `[Theory]`)
@@ -2806,7 +36,7 @@ This mirrors the Clean Architecture dependency rule — test projects never reac
2806 36
2807 37 ---
2808 38
2809 - ## 13. CI/CD Pipeline
39 + ## 11. CI/CD Pipeline
2810 40
2811 41 The CI/CD pipeline is split into two conceptual sections:
2812 42
@@ -2820,7 +50,7 @@ Configuration for JetBrains Qodana static analysis. Points to the `.slnx` soluti
2820 50 ```yaml
2821 51 #-------------------------------------------------------------------------------#
2822 52 # Qodana analysis is configured by qodana.yaml file #
2823 - # https://www.jetbrains.com/help/qodana/qodana-yaml.html #
53 + # [https://www.jetbrains.com/help/qodana/qodana-yaml.html](https://www.jetbrains.com/help/qodana/qodana-yaml.html) #
2824 54 #-------------------------------------------------------------------------------#
2825 55
2826 56 #################################################################################
@@ -2834,7 +64,7 @@ ide: QDNET
2834 64
2835 65 #Specify the .NET solution to analyze
2836 66 dotnet:
2837 - solution: {Projects}.slnx
67 + solution: ${PROJECT}.slnx
2838 68
2839 69 #Specify inspection profile for code analysis
2840 70 profile:
@@ -2855,7 +85,7 @@ profile:
2855 85
2856 86 #Install IDE plugins before Qodana execution (Applied in CI/CD pipeline)
2857 87 #plugins:
2858 - # - id: <plugin.id> #(plugin id can be found at https://plugins.jetbrains.com)
88 + # - id: <plugin.id> #(plugin id can be found at [https://plugins.jetbrains.com](https://plugins.jetbrains.com))
2859 89
2860 90 # Quality gate. Will fail the CI/CD pipeline if any condition is not met
2861 91 # severityThresholds - configures maximum thresholds for different problem severities
@@ -2886,18 +116,12 @@ on:
2886 116 env:
2887 117 DOTNET_VERSION: "10.0.x"
2888 118 JAVA_VERSION: "17"
2889 - DOCKER_IMAGE: ${{ vars.DOCKERHUB_USERNAME }}/{projects}-api
2890 - ```
2891 -
2892 - #### Job 1: Build & Test
119 + DOCKER_IMAGE: ${{ vars.DOCKERHUB_USERNAME }}/${PROJECT_LOWER}-api
2893 120
2894 - Runs on every push and PR. Spins up a PostgreSQL service container, restores, builds, and runs all tests. Test results and coverage reports are uploaded as artifacts.
2895 -
2896 - ```yaml
2897 121 jobs:
2898 - # ──────────────────────────────────────────────
122 + # ─────────────────────────────────────────────────────────────────
2899 123 # Job 1: Build, test, and collect coverage
2900 - # ──────────────────────────────────────────────
124 + # ─────────────────────────────────────────────────────────────────
2901 125 test:
2902 126 name: Build & Test
2903 127 runs-on: ubuntu-latest
@@ -2906,7 +130,7 @@ jobs:
2906 130 postgres:
2907 131 image: postgres:17-alpine
2908 132 env:
2909 - POSTGRES_DB: {projects}_test
133 + POSTGRES_DB: ${PROJECT_LOWER}_test
2910 134 POSTGRES_USER: postgres
2911 135 POSTGRES_PASSWORD: postgres
2912 136 ports:
@@ -2941,7 +165,7 @@ jobs:
2941 165 --collect:"XPlat Code Coverage"
2942 166 --results-directory ./TestResults
2943 167 env:
2944 - ConnectionStrings__DefaultConnection: "Host=localhost;Port=5432;Database={projects}_test;Username=postgres;Password=postgres"
168 + ConnectionStrings__DefaultConnection: "Host=localhost;Port=5432;Database=${PROJECT_LOWER}_test;Username=postgres;Password=postgres"
2945 169
2946 170 - name: Upload test results
2947 171 uses: actions/upload-artifact@v4
@@ -2950,16 +174,10 @@ jobs:
2950 174 name: test-results
2951 175 path: ./TestResults
2952 176 retention-days: 7
2953 - ```
2954 -
2955 - #### Job 2: SonarCloud Analysis
2956 177
2957 - Runs after tests pass. Performs static analysis and code coverage reporting via SonarCloud. Requires `SONAR_TOKEN` secret and `SONAR_PROJECT_KEY` / `SONAR_ORGANIZATION_KEY` variables.
2958 -
2959 - ```yaml
2960 - # ──────────────────────────────────────────────
178 + # ─────────────────────────────────────────────────────────────────
2961 179 # Job 2: SonarCloud analysis
2962 - # ──────────────────────────────────────────────
180 + # ─────────────────────────────────────────────────────────────────
2963 181 sonar:
2964 182 name: SonarCloud Analysis
2965 183 runs-on: ubuntu-latest
@@ -2969,7 +187,7 @@ Runs after tests pass. Performs static analysis and code coverage reporting via
2969 187 postgres:
2970 188 image: postgres:17-alpine
2971 189 env:
2972 - POSTGRES_DB: {projects}_test
190 + POSTGRES_DB: ${PROJECT_LOWER}_test
2973 191 POSTGRES_USER: postgres
2974 192 POSTGRES_PASSWORD: postgres
2975 193 ports:
@@ -3008,7 +226,7 @@ Runs after tests pass. Performs static analysis and code coverage reporting via
3008 226 /k:"${{ vars.SONAR_PROJECT_KEY }}"
3009 227 /o:"${{ vars.SONAR_ORGANIZATION_KEY }}"
3010 228 /d:sonar.token="${{ secrets.SONAR_TOKEN }}"
3011 - /d:sonar.host.url="https://sonarcloud.io"
229 + /d:sonar.host.url="[https://sonarcloud.io](https://sonarcloud.io)"
3012 230 /d:sonar.cs.opencover.reportsPaths="**/TestResults/**/coverage.opencover.xml"
3013 231 /d:sonar.exclusions="**/obj/**,**/bin/**"
3014 232 /d:sonar.coverage.exclusions="**/obj/**,**/bin/**,**/Migrations/**"
@@ -3024,7 +242,7 @@ Runs after tests pass. Performs static analysis and code coverage reporting via
3024 242 --collect:"XPlat Code Coverage;Format=opencover"
3025 243 --results-directory ./TestResults
3026 244 env:
3027 - ConnectionStrings__DefaultConnection: "Host=localhost;Port=5432;Database={projects}_test;Username=postgres;Password=postgres"
245 + ConnectionStrings__DefaultConnection: "Host=localhost;Port=5432;Database=${PROJECT_LOWER}_test;Username=postgres;Password=postgres"
3028 246
3029 247 - name: End SonarCloud analysis
3030 248 env:
@@ -3039,16 +257,10 @@ Runs after tests pass. Performs static analysis and code coverage reporting via
3039 257 scanMetadataReportFile: .sonarqube/out/.sonar/report-task.txt
3040 258 env:
3041 259 SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
3042 - ```
3043 -
3044 - #### Job 3: Qodana Analysis
3045 260
3046 - Runs in parallel with SonarCloud (both depend on `test`). Uses JetBrains Qodana for .NET static analysis. Requires `QODANA_TOKEN` secret and `contents: write` permissions for PR annotations.
3047 -
3048 - ```yaml
3049 - # ──────────────────────────────────────────────
261 + # ─────────────────────────────────────────────────────────────────
3050 262 # Job 3: Qodana analysis (parallel with SonarCloud)
3051 - # ──────────────────────────────────────────────
263 + # ─────────────────────────────────────────────────────────────────
3052 264 qodana:
3053 265 name: Qodana Analysis
3054 266 runs-on: ubuntu-latest
@@ -3069,16 +281,10 @@ Runs in parallel with SonarCloud (both depend on `test`). Uses JetBrains Qodana
3069 281 uses: JetBrains/qodana-action@v2025.1
3070 282 env:
3071 283 QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }}
3072 - ```
3073 -
3074 - #### Job 4: Deploy to Server
3075 284
3076 - Only runs on pushes to `dev` (not PRs, not `main`). Builds a Docker image, pushes it to Docker Hub, then deploys to a remote server via SSH over Tailscale. This job is project-specific — customize the deployment target, Tailscale OAuth credentials, and SSH details.
3077 -
3078 - ```yaml
3079 - # ──────────────────────────────────────────────
285 + # ─────────────────────────────────────────────────────────────────
3080 286 # Job 4: Build, push, and deploy
3081 - # ──────────────────────────────────────────────
287 + # ─────────────────────────────────────────────────────────────────
3082 288 deploy:
3083 289 name: Deploy to Server
3084 290 runs-on: ubuntu-latest
@@ -3183,7 +389,7 @@ Only runs on pushes to `dev` (not PRs, not `main`). Builds a Docker image, pushe
3183 389
3184 390 ---
3185 391
3186 - ## 14. AI-Assisted Development
392 + ## 12. AI-Assisted Development
3187 393
3188 394 ### `.github/copilot-instructions.md`
3189 395
@@ -3200,7 +406,7 @@ This file is automatically picked up by Copilot in VS Code and GitHub.com, provi
3200 406
3201 407 ---
3202 408
3203 - ## 15. Running the Project
409 + ## 13. Running the Project
3204 410
3205 411 ### Local Development (without Docker)
3206 412
@@ -3209,7 +415,7 @@ This file is automatically picked up by Copilot in VS Code and GitHub.com, provi
3209 415 docker compose up db -d
3210 416
3211 417 # Run the API
3212 - dotnet run --project src/{Projects}.Api
418 + dotnet run --project src/${PROJECT}.Api
3213 419
3214 420 # API available at http://localhost:5212
3215 421 # Health check: http://localhost:5212/health
@@ -3233,9 +439,9 @@ docker compose up --build -d
3233 439 dotnet test
3234 440
3235 441 # Specific test project
3236 - dotnet test tests/{Projects}.Domain.Tests
3237 - dotnet test tests/{Projects}.Application.Tests
3238 - dotnet test tests/{Projects}.IntegrationTests
442 + dotnet test tests/${PROJECT}.Domain.Tests
443 + dotnet test tests/${PROJECT}.Application.Tests
444 + dotnet test tests/${PROJECT}.IntegrationTests
3239 445
3240 446 # Single test by name
3241 447 dotnet test --filter "FullyQualifiedName~MyTestMethod"
@@ -3246,13 +452,13 @@ dotnet test --filter "FullyQualifiedName~MyTestMethod"
3246 452 ```bash
3247 453 # Add a new migration
3248 454 dotnet ef migrations add <MigrationName> \
3249 - --project src/{Projects}.Infrastructure \
3250 - --startup-project src/{Projects}.Api
455 + --project src/${PROJECT}.Infrastructure \
456 + --startup-project src/${PROJECT}.Api
3251 457
3252 458 # Apply migrations
3253 459 dotnet ef database update \
3254 - --project src/{Projects}.Infrastructure \
3255 - --startup-project src/{Projects}.Api
460 + --project src/${PROJECT}.Infrastructure \
461 + --startup-project src/${PROJECT}.Api
3256 462 ```
3257 463
3258 464 ---

weehong bu gisti düzenledi 5 months ago. Düzenlemeye git

1 file changed, 342 insertions, 45 deletions

dotnet-10-clean-architecture-boilerplate-guide.md

@@ -348,86 +348,383 @@ root = true
348 348 # All files
349 349 [*]
350 350 indent_style = space
351 - indent_size = 4
352 - end_of_line = lf
353 - charset = utf-8
354 - trim_trailing_whitespace = true
355 - insert_final_newline = true
356 351
357 - # XML project files
358 - [*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj,props,targets}]
352 + # Xml files
353 + [*.{xml,csproj,props,targets,ruleset,nuspec,resx}]
359 354 indent_size = 2
360 355
361 - # XML files
362 - [*.{xml,config,nuspec,resx}]
356 + # Javascript files
357 + [*.js]
363 358 indent_size = 2
364 359
365 - # JSON files
366 - [*.json]
360 + # Json files
361 + [*.{json,config,nswag}]
367 362 indent_size = 2
368 363
369 - # YAML files
370 - [*.{yml,yaml}]
371 - indent_size = 2
372 -
373 - # Markdown files
374 - [*.md]
375 - trim_trailing_whitespace = false
376 -
377 364 # C# files
378 365 [*.cs]
379 366
367 + #### Core EditorConfig Options ####
368 +
369 + # Indentation and spacing
370 + indent_size = 4
371 + tab_width = 4
372 +
373 + # New line preferences
374 + end_of_line = lf
375 + insert_final_newline = true
376 +
377 + #### .NET Coding Conventions ####
378 + [*.{cs,vb}]
379 +
380 380 # Organize usings
381 - dotnet_sort_system_directives_first = true
382 381 dotnet_separate_import_directive_groups = false
382 + dotnet_sort_system_directives_first = true
383 + file_header_template = unset
384 +
385 + # this. and Me. preferences
386 + dotnet_style_qualification_for_event = false:silent
387 + dotnet_style_qualification_for_field = false:silent
388 + dotnet_style_qualification_for_method = false:silent
389 + dotnet_style_qualification_for_property = false:silent
390 +
391 + # Language keywords vs BCL types preferences
392 + dotnet_style_predefined_type_for_locals_parameters_members = true:silent
393 + dotnet_style_predefined_type_for_member_access = true:silent
383 394
384 - # Namespace settings
385 - csharp_style_namespace_declarations = file_scoped:warning
395 + # Parentheses preferences
396 + dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent
397 + dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent
398 + dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent
399 + dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent
400 +
401 + # Modifier preferences
402 + dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent
403 +
404 + # Expression-level preferences
405 + dotnet_style_coalesce_expression = true:suggestion
406 + dotnet_style_collection_initializer = true:suggestion
407 + dotnet_style_explicit_tuple_names = true:suggestion
408 + dotnet_style_null_propagation = true:suggestion
409 + dotnet_style_object_initializer = true:suggestion
410 + dotnet_style_operator_placement_when_wrapping = beginning_of_line
411 + dotnet_style_prefer_auto_properties = true:suggestion
412 + dotnet_style_prefer_compound_assignment = true:suggestion
413 + dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion
414 + dotnet_style_prefer_conditional_expression_over_return = true:suggestion
415 + dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
416 + dotnet_style_prefer_inferred_tuple_names = true:suggestion
417 + dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
418 + dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
419 + dotnet_style_prefer_simplified_interpolation = true:suggestion
420 +
421 + # Field preferences
422 + dotnet_style_readonly_field = true:warning
423 +
424 + # Parameter preferences
425 + dotnet_code_quality_unused_parameters = all:suggestion
426 +
427 + # Suppression preferences
428 + dotnet_remove_unnecessary_suppression_exclusions = none
429 +
430 + #### C# Coding Conventions ####
431 + [*.cs]
386 432
387 433 # var preferences
388 - csharp_style_var_for_built_in_types = true:suggestion
434 + csharp_style_var_elsewhere = false:silent
435 + csharp_style_var_for_built_in_types = false:silent
389 436 csharp_style_var_when_type_is_apparent = true:suggestion
390 - csharp_style_var_elsewhere = true:suggestion
391 437
392 - # Expression-level preferences
393 - csharp_prefer_simple_using_statement = true:warning
438 + # Expression-bodied members
439 + csharp_style_expression_bodied_accessors = true:silent
440 + csharp_style_expression_bodied_constructors = true:suggestion
441 + csharp_style_expression_bodied_indexers = true:silent
442 + csharp_style_expression_bodied_lambdas = true:suggestion
443 + csharp_style_expression_bodied_local_functions = true:suggestion
444 + csharp_style_expression_bodied_methods = true:suggestion
445 + csharp_style_expression_bodied_operators = true:suggestion
446 + csharp_style_expression_bodied_properties = true:silent
447 +
448 + # Pattern matching preferences
449 + csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
450 + csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
451 + csharp_style_prefer_not_pattern = true:suggestion
452 + csharp_style_prefer_pattern_matching = true:silent
394 453 csharp_style_prefer_switch_expression = true:suggestion
395 - csharp_style_prefer_pattern_matching = true:suggestion
396 454
397 455 # Null-checking preferences
398 - csharp_style_throw_expression = true:suggestion
399 456 csharp_style_conditional_delegate_call = true:suggestion
400 457
458 + # Modifier preferences
459 + csharp_prefer_static_local_function = true:warning
460 + csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:silent
461 +
462 + # Code-block preferences
463 + csharp_prefer_braces = true:silent
464 + csharp_prefer_simple_using_statement = true:suggestion
465 +
466 + # Expression-level preferences
467 + csharp_prefer_simple_default_expression = true:suggestion
468 + csharp_style_deconstructed_variable_declaration = true:suggestion
469 + csharp_style_inlined_variable_declaration = true:suggestion
470 + csharp_style_pattern_local_over_anonymous_function = true:suggestion
471 + csharp_style_prefer_index_operator = true:suggestion
472 + csharp_style_prefer_range_operator = true:suggestion
473 + csharp_style_throw_expression = true:suggestion
474 + csharp_style_unused_value_assignment_preference = discard_variable:suggestion
475 + csharp_style_unused_value_expression_statement_preference = discard_variable:silent
476 +
477 + # 'using' directive preferences
478 + csharp_using_directive_placement = outside_namespace:silent
479 +
480 + #### C# Formatting Rules ####
481 +
401 482 # New line preferences
402 - csharp_new_line_before_open_brace = all
403 - csharp_new_line_before_else = true
404 483 csharp_new_line_before_catch = true
484 + csharp_new_line_before_else = true
405 485 csharp_new_line_before_finally = true
486 + csharp_new_line_before_members_in_anonymous_types = true
487 + csharp_new_line_before_members_in_object_initializers = true
488 + csharp_new_line_before_open_brace = all
489 + csharp_new_line_between_query_expression_clauses = true
406 490
407 491 # Indentation preferences
492 + csharp_indent_block_contents = true
493 + csharp_indent_braces = false
408 494 csharp_indent_case_contents = true
495 + csharp_indent_case_contents_when_block = true
496 + csharp_indent_labels = one_less_than_current
409 497 csharp_indent_switch_labels = true
410 498
411 - # Naming conventions
412 - dotnet_naming_rule.interface_should_be_begins_with_i.severity = warning
413 - dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
414 - dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
499 + # Space preferences
500 + csharp_space_after_cast = false
501 + csharp_space_after_colon_in_inheritance_clause = true
502 + csharp_space_after_comma = true
503 + csharp_space_after_dot = false
504 + csharp_space_after_keywords_in_control_flow_statements = true
505 + csharp_space_after_semicolon_in_for_statement = true
506 + csharp_space_around_binary_operators = before_and_after
507 + csharp_space_around_declaration_statements = false
508 + csharp_space_before_colon_in_inheritance_clause = true
509 + csharp_space_before_comma = false
510 + csharp_space_before_dot = false
511 + csharp_space_before_open_square_brackets = false
512 + csharp_space_before_semicolon_in_for_statement = false
513 + csharp_space_between_empty_square_brackets = false
514 + csharp_space_between_method_call_empty_parameter_list_parentheses = false
515 + csharp_space_between_method_call_name_and_opening_parenthesis = false
516 + csharp_space_between_method_call_parameter_list_parentheses = false
517 + csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
518 + csharp_space_between_method_declaration_name_and_open_parenthesis = false
519 + csharp_space_between_method_declaration_parameter_list_parentheses = false
520 + csharp_space_between_parentheses = false
521 + csharp_space_between_square_brackets = false
522 +
523 + # Wrapping preferences
524 + csharp_preserve_single_line_blocks = true
525 + csharp_preserve_single_line_statements = true
526 + csharp_style_namespace_declarations = file_scoped:suggestion
527 + csharp_style_prefer_method_group_conversion = true:silent
528 + csharp_style_prefer_top_level_statements = true:silent
529 + csharp_style_prefer_primary_constructors = true:warning
530 + csharp_style_prefer_null_check_over_type_check = true:suggestion
531 + csharp_style_prefer_local_over_anonymous_function = true:suggestion
532 + csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion
533 + csharp_style_prefer_tuple_swap = true:suggestion
534 + csharp_style_prefer_utf8_string_literals = true:suggestion
535 +
536 + #### Naming styles ####
537 + [*.{cs,vb}]
538 +
539 + # Naming rules
540 +
541 + dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.severity = suggestion
542 + dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.symbols = types_and_namespaces
543 + dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.style = pascalcase
544 +
545 + dotnet_naming_rule.interfaces_should_be_ipascalcase.severity = suggestion
546 + dotnet_naming_rule.interfaces_should_be_ipascalcase.symbols = interfaces
547 + dotnet_naming_rule.interfaces_should_be_ipascalcase.style = ipascalcase
548 +
549 + dotnet_naming_rule.type_parameters_should_be_tpascalcase.severity = suggestion
550 + dotnet_naming_rule.type_parameters_should_be_tpascalcase.symbols = type_parameters
551 + dotnet_naming_rule.type_parameters_should_be_tpascalcase.style = tpascalcase
552 +
553 + dotnet_naming_rule.methods_should_be_pascalcase.severity = suggestion
554 + dotnet_naming_rule.methods_should_be_pascalcase.symbols = methods
555 + dotnet_naming_rule.methods_should_be_pascalcase.style = pascalcase
556 +
557 + dotnet_naming_rule.properties_should_be_pascalcase.severity = suggestion
558 + dotnet_naming_rule.properties_should_be_pascalcase.symbols = properties
559 + dotnet_naming_rule.properties_should_be_pascalcase.style = pascalcase
560 +
561 + dotnet_naming_rule.events_should_be_pascalcase.severity = suggestion
562 + dotnet_naming_rule.events_should_be_pascalcase.symbols = events
563 + dotnet_naming_rule.events_should_be_pascalcase.style = pascalcase
564 +
565 + dotnet_naming_rule.local_variables_should_be_camelcase.severity = suggestion
566 + dotnet_naming_rule.local_variables_should_be_camelcase.symbols = local_variables
567 + dotnet_naming_rule.local_variables_should_be_camelcase.style = camelcase
568 +
569 + dotnet_naming_rule.local_constants_should_be_camelcase.severity = suggestion
570 + dotnet_naming_rule.local_constants_should_be_camelcase.symbols = local_constants
571 + dotnet_naming_rule.local_constants_should_be_camelcase.style = camelcase
572 +
573 + dotnet_naming_rule.parameters_should_be_camelcase.severity = suggestion
574 + dotnet_naming_rule.parameters_should_be_camelcase.symbols = parameters
575 + dotnet_naming_rule.parameters_should_be_camelcase.style = camelcase
576 +
577 + dotnet_naming_rule.public_fields_should_be_pascalcase.severity = suggestion
578 + dotnet_naming_rule.public_fields_should_be_pascalcase.symbols = public_fields
579 + dotnet_naming_rule.public_fields_should_be_pascalcase.style = pascalcase
580 +
581 + dotnet_naming_rule.private_fields_should_be__camelcase.severity = suggestion
582 + dotnet_naming_rule.private_fields_should_be__camelcase.symbols = private_fields
583 + dotnet_naming_rule.private_fields_should_be__camelcase.style = _camelcase
584 +
585 + dotnet_naming_rule.private_static_fields_should_be_s_camelcase.severity = suggestion
586 + dotnet_naming_rule.private_static_fields_should_be_s_camelcase.symbols = private_static_fields
587 + dotnet_naming_rule.private_static_fields_should_be_s_camelcase.style = s_camelcase
588 +
589 + dotnet_naming_rule.public_constant_fields_should_be_pascalcase.severity = suggestion
590 + dotnet_naming_rule.public_constant_fields_should_be_pascalcase.symbols = public_constant_fields
591 + dotnet_naming_rule.public_constant_fields_should_be_pascalcase.style = pascalcase
592 +
593 + dotnet_naming_rule.private_constant_fields_should_be_pascalcase.severity = suggestion
594 + dotnet_naming_rule.private_constant_fields_should_be_pascalcase.symbols = private_constant_fields
595 + dotnet_naming_rule.private_constant_fields_should_be_pascalcase.style = pascalcase
596 +
597 + dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.severity = suggestion
598 + dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.symbols = public_static_readonly_fields
599 + dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.style = pascalcase
600 +
601 + dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.severity = suggestion
602 + dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.symbols = private_static_readonly_fields
603 + dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.style = pascalcase
604 +
605 + dotnet_naming_rule.enums_should_be_pascalcase.severity = suggestion
606 + dotnet_naming_rule.enums_should_be_pascalcase.symbols = enums
607 + dotnet_naming_rule.enums_should_be_pascalcase.style = pascalcase
608 +
609 + dotnet_naming_rule.local_functions_should_be_pascalcase.severity = suggestion
610 + dotnet_naming_rule.local_functions_should_be_pascalcase.symbols = local_functions
611 + dotnet_naming_rule.local_functions_should_be_pascalcase.style = pascalcase
612 +
613 + dotnet_naming_rule.non_field_members_should_be_pascalcase.severity = suggestion
614 + dotnet_naming_rule.non_field_members_should_be_pascalcase.symbols = non_field_members
615 + dotnet_naming_rule.non_field_members_should_be_pascalcase.style = pascalcase
616 +
617 + # Symbol specifications
618 +
619 + dotnet_naming_symbols.interfaces.applicable_kinds = interface
620 + dotnet_naming_symbols.interfaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
621 + dotnet_naming_symbols.interfaces.required_modifiers =
622 +
623 + dotnet_naming_symbols.enums.applicable_kinds = enum
624 + dotnet_naming_symbols.enums.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
625 + dotnet_naming_symbols.enums.required_modifiers =
626 +
627 + dotnet_naming_symbols.events.applicable_kinds = event
628 + dotnet_naming_symbols.events.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
629 + dotnet_naming_symbols.events.required_modifiers =
630 +
631 + dotnet_naming_symbols.methods.applicable_kinds = method
632 + dotnet_naming_symbols.methods.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
633 + dotnet_naming_symbols.methods.required_modifiers =
634 +
635 + dotnet_naming_symbols.properties.applicable_kinds = property
636 + dotnet_naming_symbols.properties.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
637 + dotnet_naming_symbols.properties.required_modifiers =
638 +
639 + dotnet_naming_symbols.public_fields.applicable_kinds = field
640 + dotnet_naming_symbols.public_fields.applicable_accessibilities = public, internal
641 + dotnet_naming_symbols.public_fields.required_modifiers =
642 +
643 + dotnet_naming_symbols.private_fields.applicable_kinds = field
644 + dotnet_naming_symbols.private_fields.applicable_accessibilities = private, protected, protected_internal, private_protected
645 + dotnet_naming_symbols.private_fields.required_modifiers =
646 +
647 + dotnet_naming_symbols.private_static_fields.applicable_kinds = field
648 + dotnet_naming_symbols.private_static_fields.applicable_accessibilities = private, protected, protected_internal, private_protected
649 + dotnet_naming_symbols.private_static_fields.required_modifiers = static
650 +
651 + dotnet_naming_symbols.types_and_namespaces.applicable_kinds = namespace, class, struct, interface, enum
652 + dotnet_naming_symbols.types_and_namespaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
653 + dotnet_naming_symbols.types_and_namespaces.required_modifiers =
654 +
655 + dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
656 + dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
657 + dotnet_naming_symbols.non_field_members.required_modifiers =
658 +
659 + dotnet_naming_symbols.type_parameters.applicable_kinds = type_parameter
660 + dotnet_naming_symbols.type_parameters.applicable_accessibilities = *
661 + dotnet_naming_symbols.type_parameters.required_modifiers =
662 +
663 + dotnet_naming_symbols.private_constant_fields.applicable_kinds = field
664 + dotnet_naming_symbols.private_constant_fields.applicable_accessibilities = private, protected, protected_internal, private_protected
665 + dotnet_naming_symbols.private_constant_fields.required_modifiers = const
666 +
667 + dotnet_naming_symbols.local_variables.applicable_kinds = local
668 + dotnet_naming_symbols.local_variables.applicable_accessibilities = local
669 + dotnet_naming_symbols.local_variables.required_modifiers =
670 +
671 + dotnet_naming_symbols.local_constants.applicable_kinds = local
672 + dotnet_naming_symbols.local_constants.applicable_accessibilities = local
673 + dotnet_naming_symbols.local_constants.required_modifiers = const
674 +
675 + dotnet_naming_symbols.parameters.applicable_kinds = parameter
676 + dotnet_naming_symbols.parameters.applicable_accessibilities = *
677 + dotnet_naming_symbols.parameters.required_modifiers =
678 +
679 + dotnet_naming_symbols.public_constant_fields.applicable_kinds = field
680 + dotnet_naming_symbols.public_constant_fields.applicable_accessibilities = public, internal
681 + dotnet_naming_symbols.public_constant_fields.required_modifiers = const
682 +
683 + dotnet_naming_symbols.public_static_readonly_fields.applicable_kinds = field
684 + dotnet_naming_symbols.public_static_readonly_fields.applicable_accessibilities = public, internal
685 + dotnet_naming_symbols.public_static_readonly_fields.required_modifiers = readonly, static
686 +
687 + dotnet_naming_symbols.private_static_readonly_fields.applicable_kinds = field
688 + dotnet_naming_symbols.private_static_readonly_fields.applicable_accessibilities = private, protected, protected_internal, private_protected
689 + dotnet_naming_symbols.private_static_readonly_fields.required_modifiers = readonly, static
690 +
691 + dotnet_naming_symbols.local_functions.applicable_kinds = local_function
692 + dotnet_naming_symbols.local_functions.applicable_accessibilities = *
693 + dotnet_naming_symbols.local_functions.required_modifiers =
694 +
695 + # Naming styles
696 +
697 + dotnet_naming_style.pascalcase.required_prefix =
698 + dotnet_naming_style.pascalcase.required_suffix =
699 + dotnet_naming_style.pascalcase.word_separator =
700 + dotnet_naming_style.pascalcase.capitalization = pascal_case
701 +
702 + dotnet_naming_style.ipascalcase.required_prefix = I
703 + dotnet_naming_style.ipascalcase.required_suffix =
704 + dotnet_naming_style.ipascalcase.word_separator =
705 + dotnet_naming_style.ipascalcase.capitalization = pascal_case
415 706
416 - dotnet_naming_rule.private_field_should_be_camel_case_with_underscore.severity = warning
417 - dotnet_naming_rule.private_field_should_be_camel_case_with_underscore.symbols = private_field
418 - dotnet_naming_rule.private_field_should_be_camel_case_with_underscore.style = camel_case_with_underscore
707 + dotnet_naming_style.tpascalcase.required_prefix = T
708 + dotnet_naming_style.tpascalcase.required_suffix =
709 + dotnet_naming_style.tpascalcase.word_separator =
710 + dotnet_naming_style.tpascalcase.capitalization = pascal_case
419 711
420 - dotnet_naming_symbols.interface.applicable_kinds = interface
421 - dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
712 + dotnet_naming_style._camelcase.required_prefix = _
713 + dotnet_naming_style._camelcase.required_suffix =
714 + dotnet_naming_style._camelcase.word_separator =
715 + dotnet_naming_style._camelcase.capitalization = camel_case
422 716
423 - dotnet_naming_symbols.private_field.applicable_kinds = field
424 - dotnet_naming_symbols.private_field.applicable_accessibilities = private, private_protected
717 + dotnet_naming_style.camelcase.required_prefix =
718 + dotnet_naming_style.camelcase.required_suffix =
719 + dotnet_naming_style.camelcase.word_separator =
720 + dotnet_naming_style.camelcase.capitalization = camel_case
425 721
426 - dotnet_naming_style.begins_with_i.required_prefix = I
427 - dotnet_naming_style.begins_with_i.capitalization = pascal_case
722 + dotnet_naming_style.s_camelcase.required_prefix = s_
723 + dotnet_naming_style.s_camelcase.required_suffix =
724 + dotnet_naming_style.s_camelcase.word_separator =
725 + dotnet_naming_style.s_camelcase.capitalization = camel_case
428 726
429 - dotnet_naming_style.camel_case_with_underscore.required_prefix = _
430 - dotnet_naming_style.camel_case_with_underscore.capitalization = camel_case
727 + dotnet_style_namespace_match_folder = true:suggestion
431 728 ```
432 729
433 730 ### `.dockerignore`
Daha yeni Daha eski