Skip to content
المشاريع

phongnguyend/Practical.CleanArchitecture

عرض على GitHub

حول

معمارية Clean Architecture متكاملة باستخدام ‎.NET 10، تشمل Microservices وModular Monolith وMonolith، وBlazor وAngular 22 وReact 19 وVue 3.5، وBFF مع YARP، وNextJs 16، وتطبيقات الجوال باستخدام React Native وFlutter وKotlin وMAUI وCapacitor، بالإضافة إلى التصميم الموجّه بالمجال (Domain-Driven Design)، وCQRS، وSOLID، وOpenID Connect، وEF Core، وOpenTelemetry، وSignalR، وفحوصات الصحة، وتحديد معدل الطلبات، والسحابة عبر Azure وAWS وGCP، ...

تطوير الويب والتطبيقات

كيف تُقاس هذه الأرقام

النمو المقاس للنجوم

خلال 24 ساعة
؜-١
خلال 7 أيام
؜-١
خلال 15 يومًا
٠
خلال شهر
؜-١

تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.

README.md

الأصل

:warning: Warning

The code samples contain multiple ways and patterns to do things and not always be considered best practices or recommended for all situations.

Database Centric vs Domain Centric Architecture

alt text

(open on draw.io)

Hexagonal Architecture

alt text

(open on draw.io)

Onion Architecture

alt text

(open on draw.io)

The Clean Architecture

alt text

(open on draw.io)

Classic Three-layer Architecture

alt text

(open on draw.io)

Modern Four-layer Architecture

alt text

(open on draw.io)

Layer Dependencies

alt text

(open on draw.io)

Layer Examples

alt text

(open on draw.io)

Testing Pyramid

alt text alt text alt text

(open on draw.io)

Vertical Slice Architecture (Modular Monolith)

alt text

(open on draw.io)

Solution Structure

alt text

alt text

alt text

How to Run:

Update Configuration

Additional Configuration Sources
  • Open ClassifiedAds.WebMVC/appsettings.json and jump to ConfigurationSources section.

    "ConfigurationSources": {
      "SqlServer": {
        "IsEnabled": false,
        "ConnectionString": "Server=127.0.0.1;Database=ClassifiedAds;User Id=sa;Password=sqladmin123!@#",
        "SqlQuery": "select [Key], [Value] from ConfigurationEntries"
      },
      "AzureKeyVault": {
        "IsEnabled": false,
        "VaultName": "https://xxx.vault.azure.net/"
      }
    },
    
  • Get from Sql Server database:

    "ConfigurationSources": {
      "SqlServer": {
        "IsEnabled": true,
        "ConnectionString": "Server=127.0.0.1;Database=ClassifiedAds;User Id=sa;Password=sqladmin123!@#",
        "SqlQuery": "select [Key], [Value] from ConfigurationEntries"
      },
    },
    
  • Get from Azure Key Vault:

    "ConfigurationSources": {
      "AzureKeyVault": {
        "IsEnabled": true,
        "VaultName": "https://xxx.vault.azure.net/"
      }
    },
    
  • Use Both:

    "ConfigurationSources": {
      "SqlServer": {
        "IsEnabled": true,
        "ConnectionString": "Server=127.0.0.1;Database=ClassifiedAds;User Id=sa;Password=sqladmin123!@#",
        "SqlQuery": "select [Key], [Value] from ConfigurationEntries"
      },
      "AzureKeyVault": {
        "IsEnabled": true,
        "VaultName": "https://xxx.vault.azure.net/"
      }
    },
    
Storage
  • Open ClassifiedAds.WebMVC/appsettings.json, ClassifiedAds.WebAPI/appsettings.json and jump to Storage section.

    "Storage": {
      "Provider": "Local",
    },
    
  • Use Local Files:

    "Storage": {
      "Provider": "Local",
      "Local": {
        "Path": "E:\\files"
      },
    },
    
  • Use Azure Blob:

    "Storage": {
      "Provider": "Azure",
      "Azure": {
        "ConnectionString": "xxx",
        "Container": "classifiedadds"
      },
    },
    
  • Use Amazon S3:

    "Storage": {
      "Provider": "Amazon",
      "Amazon": {
        "AccessKeyID": "xxx",
        "SecretAccessKey": "xxx",
        "BucketName": "classifiedadds",
        "RegionEndpoint": "ap-southeast-1"
      }
    },
    
Message Broker
  • Open below files and jump to Messaging section:

    "Messaging": {
      "Provider": "RabbitMQ",
    }
    
  • Use RabbitMQ

    "Messaging": {
      "Provider": "RabbitMQ",
      "RabbitMQ": {
        "HostName": "localhost",
        "UserName": "guest",
        "Password": "guest",
        "ExchangeName": "amq.direct",
        "RoutingKeys": {
          "FileUploadedEvent": "classifiedadds_fileuploaded",
          "FileDeletedEvent": "classifiedadds_filedeleted",
          "EmailMessageCreatedEvent": "classifiedadds_emailcreated",
          "SmsMessageCreatedEvent": "classifiedadds_smscreated"
        },
        "QueueNames": {
          "FileUploadedEvent": "classifiedadds_fileuploaded",
          "FileDeletedEvent": "classifiedadds_filedeleted",
          "EmailMessageCreatedEvent": "classifiedadds_emailcreated",
          "SmsMessageCreatedEvent": "classifiedadds_smscreated"
        }
      }
    }
    
  • Use Kafka:

    "Messaging": {
      "Provider": "Kafka",
      "Kafka": {
        "BootstrapServers": "localhost:9092",
        "Topics": {
          "FileUploadedEvent": "classifiedadds_fileuploaded",
          "FileDeletedEvent": "classifiedadds_filedeleted",
          "EmailMessageCreatedEvent": "classifiedadds_emailcreated",
          "SmsMessageCreatedEvent": "classifiedadds_smscreated"
        },
      }
    }
    
  • Use Azure Queue Storage:

    "Messaging": {
      "Provider": "AzureQueue",
      "AzureQueue": {
        "ConnectionString": "xxx",
        "QueueNames": {
          "FileUploadedEvent": "classifiedadds-fileuploaded",
          "FileDeletedEvent": "classifiedadds-filedeleted",
          "EmailMessageCreatedEvent": "classifiedadds-emailcreated",
          "SmsMessageCreatedEvent": "classifiedadds-smscreated"
        }
      }
    }
    
  • Use Azure Service Bus:

    "Messaging": {
      "Provider": "AzureServiceBus",
      "AzureServiceBus": {
        "ConnectionString": "xxx",
        "QueueNames": {
          "FileUploadedEvent": "classifiedadds_fileuploaded",
          "FileDeletedEvent": "classifiedadds_filedeleted",
          "EmailMessageCreatedEvent": "classifiedadds_emailcreated",
          "SmsMessageCreatedEvent": "classifiedadds_smscreated"
        }
      }
    }
    
Logging
  • Open and jump to Logging section of below files:
    "Logging": {
      "LogLevel": {
        "Default": "Warning"
      },
      "File": {
        "MinimumLogEventLevel": "Information"
      },
      "Elasticsearch": {
        "IsEnabled": false,
        "Host": "http://localhost:9200",
        "IndexFormat": "classifiedads",
        "MinimumLogEventLevel": "Information"
      },
      "EventLog": {
        "IsEnabled": false,
        "LogName": "Application",
        "SourceName": "ClassifiedAds.WebAPI"
      }
    },
    
  • Write to Local file (./logs/log.txt). Always enabled.
    "Logging": {
      "File": {
        "MinimumLogEventLevel": "Information"
      },
    },
    
  • Write to Elasticsearch:
    "Logging": {
      "Elasticsearch": {
        "IsEnabled": true,
        "Host": "http://localhost:9200",
        "IndexFormat": "classifiedads",
        "MinimumLogEventLevel": "Information"
      },
    },
    
  • Write to Windows Event Log (Windows only):
    "Logging": {
      "EventLog": {
        "IsEnabled": true,
        "LogName": "Application",
        "SourceName": "ClassifiedAds.WebAPI"
      }
    },
    
  • Enable all options:
    "Logging": {
      "LogLevel": {
        "Default": "Warning"
      },	
      "File": {
        "MinimumLogEventLevel": "Information"
      },
      "Elasticsearch": {
        "IsEnabled": true,
        "Host": "http://localhost:9200",
        "IndexFormat": "classifiedads",
        "MinimumLogEventLevel": "Information"
      },
      "EventLog": {
        "IsEnabled": true,
        "LogName": "Application",
        "SourceName": "ClassifiedAds.WebAPI"
      }
    },
    
Caching
  • Open and jump to Caching section of below files:
    "Caching": {
      "InMemory": {
    
      },
      "Distributed": {
    
      }
    },
    
  • Configure options for In Memory Cache:
    "Caching": {
      "InMemory": {
        "SizeLimit": null
      },
    },
    
  • Use In Memory Distributed Cache (For Local Testing):
    "Caching": {
      "Distributed": {
        "Provider": "InMemory",
        "InMemory": {
          "SizeLimit": null
        }
      }
    },
    
  • Use Redis Distributed Cache:
    "Caching": {
      "Distributed": {
        "Provider": "Redis",
        "Redis": {
          "Configuration": "xxx.redis.cache.windows.net:6380,password=xxx,ssl=True,abortConnect=False",
          "InstanceName": ""
        }
      }
    },
    
  • Use Sql Server Distributed Cache:
    dotnet tool install --global dotnet-sql-cache --version="5.0"
    dotnet sql-cache create "Server=127.0.0.1;Database=ClassifiedAds;User Id=sa;Password=sqladmin123!@#" dbo CacheEntries
    
    "Caching": {
      "Distributed": {
        "Provider": "SqlServer",
        "SqlServer": {
          "ConnectionString": "Server=127.0.0.1;Database=ClassifiedAds;User Id=sa;Password=sqladmin123!@#",
          "SchemaName": "dbo",
          "TableName": "CacheEntries"
        }
      }
    },
    
Monitoring
  • Open and jump to Monitoring section of below files:
    "Monitoring": {
    
    },
    
  • Use Azure Application Insights:
    "Monitoring": {
      "AzureApplicationInsights": {
        "IsEnabled": true,
        "InstrumentationKey": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
        "EnableSqlCommandTextInstrumentation": true
      }
    },
    
  • Use OpenTelemetry:
    "Monitoring": {
      "OpenTelemetry": {
        "IsEnabled": true,
        "ServiceName": "ClassifiedAds.WebAPI",
        "TraceEnabled": true,
        "MetricEnabled": true,
        "Otlp": {
          "IsEnabled": false,
          "Endpoint": "http://localhost:4317"
        }
      }
    },
    
  • Use Both:
    "Monitoring": {
      "AzureApplicationInsights": {
        "IsEnabled": true,
        "InstrumentationKey": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
        "EnableSqlCommandTextInstrumentation": true
      },
      "OpenTelemetry": {
        "IsEnabled": true,
        "ServiceName": "ClassifiedAds.WebAPI",
        "TraceEnabled": true,
        "MetricEnabled": true,
        "Otlp": {
          "IsEnabled": false,
          "Endpoint": "http://localhost:4317"
        }
      }
    },
    
Interceptors
Security Headers
  • Open ClassifiedAds.WebAPI/appsettings.json and jump to SecurityHeaders section:
    "SecurityHeaders": {
      "Cache-Control": "no-cache, no-store, must-revalidate",
      "Pragma": "no-cache",
      "Expires": "0"
    },
    
  • Open ClassifiedAds.WebMVC/appsettings.json and jump to SecurityHeaders section:
    "SecurityHeaders": {
      "Content-Security-Policy": "form-action 'self'; frame-ancestors 'none'",
      "Feature-Policy": "camera 'none'",
      "Referrer-Policy": "strict-origin-when-cross-origin",
      "X-Content-Type-Options": "nosniff",
      "X-Frame-Options": "DENY",
      "X-XSS-Protection": "1; mode=block",
      "Cache-Control": "no-cache, no-store, must-revalidate",
      "Pragma": "no-cache",
      "Expires": "0"
    },
    
Cross-Origin Resource Sharing (CORS)
  • Open ClassifiedAds.WebAPI/appsettings.json and jump to CORS section:
    "CORS": {
      "AllowAnyOrigin": false,
      "AllowedOrigins": [ "http://localhost:4200", "http://localhost:3000", "http://localhost:8080" ]
    },
    
External Login
  • Open ClassifiedAds.IdentityServer/appsettings.json and jump to ExternalLogin section:
    "ExternalLogin": {
      "AzureActiveDirectory": {
        "IsEnabled": true,
        "Authority": "https://login.microsoftonline.com/<Directory (tenant) ID>",
        "ClientId": "<Application (client) ID",
        "ClientSecret": "xxx"
      },
      "Microsoft": {
        "IsEnabled": true,
        "ClientId": "<Application (client) ID",
        "ClientSecret": "xxx"
      },
      "Google": {
        "IsEnabled": true,
        "ClientId": "xxx",
        "ClientSecret": "xxx"
      },
      "Facebook": {
        "IsEnabled": true,
        "AppId": "xxx",
        "AppSecret": "xxx"
      }
    },
    
Sending Email
  • Open ClassifiedAds.Background/appsettings.json and jump to Notification -> Email section:
    "Notification": {
      "Email": {
        "Provider": "Fake",
      }
    }
    
  • Use SmtpClient:
    "Notification": {
      "Email": {
        "Provider": "SmtpClient",
        "SmtpClient": {
          "Host": "localhost",
          "Port": "",
          "UserName": "",
          "Password": "",
          "EnableSsl": ""
        }
      }
    }
    
Sending SMS
  • Open ClassifiedAds.Background/appsettings.json and jump to Notification -> Sms section:
    "Notification": {
      "Sms": {
        "Provider": "Fake",
      }
    }
    
  • Use Twilio
    "Notification": {
      "Sms": {
        "Provider": "Twilio",
        "Twilio": {
          "AccountSId": "",
          "AuthToken": "",
          "FromNumber": ""
        }
      }
    }
    

Run or Debug the Solution

How to Build and Run Single Page Applications:

  • Angular:

    • Navigate to folder: UIs/angular/

      npm install
      ng serve
      
    • Update environment.ts & environment.prod.ts

      export const environment = {
        OpenIdConnect: {
          Authority: "https://localhost:44367",
          ClientId: "ClassifiedAds.Angular"
        },
        ResourceServer: {
          Endpoint: "https://localhost:44312/api/"
        },
        CurrentUrl: "http://localhost:4200/"
      };
      
    • Go to http://localhost:4200/

      alt text

  • React:

    • Navigate to folder: UIs/reactjs/

      npm install
      npm run dev
      
    • Update environment.dev.tsx & environment.tsx

      const environment = {
          OpenIdConnect: {
              Authority: "https://localhost:44367",
              ClientId: "ClassifiedAds.React"
          },
          ResourceServer: {
              Endpoint: "https://localhost:44312/api/"
          },
          CurrentUrl: "http://localhost:3000/"
      };
      export default environment;
      
    • Go to http://localhost:3000/

      alt text

  • Vue:

    • Navigate to folder: UIs/vuejs/
      npm install
      npm run dev
      
    • Update environment.dev.ts & environment.dev.ts
      const environment = {
          OpenIdConnect: {
              Authority: "https://localhost:44367",
              ClientId: "ClassifiedAds.Vue"
          },
          ResourceServer: {
              Endpoint: "https://localhost:44312/api/"
          },
          CurrentUrl: "http://localhost:8080/"
      };
      export default environment;
      

How to Run on Docker Containers:

How to Run Integration & End to End Tests:

Start the API, Identity Server, and their required database/storage services. Use a development test account with permissions for the features being tested. PDF export tests also require the HTML-to-PDF service. The commands below use PowerShell and start from the repository root unless noted otherwise.

API end-to-end tests (.NET)

Requires the .NET 10 SDK. Configure appsettings.json in the current API test project:

  • OpenIdConnect: Identity Server authority, client ID/secret, and HTTPS metadata setting. The client must allow the password grant used by this suite.
  • WebAPI.Endpoint: API origin, for example https://localhost:44312 (without /api/).
  • Login: test username, password, and API scope.
dotnet test src/e2e/api/dotnet/ClassifiedAds.ApiIntegrationTests --logger trx

This suite writes product, configuration, file, and user records, exports/imports files, and requests confirmation/reset emails for its test user. Run it against a disposable test environment with a Fake email provider or test mail sink. Keep local credentials out of commits.

API end-to-end tests (TypeScript)

Requires Node.js 22.13+; no browser installation is needed. Configure the ignored .env file with the API URL (including /api/), OIDC client credentials, and test account, or provide an access token.

cd src/e2e/api/node
npm ci
Copy-Item .env.example .env # First-time setup; edit .env before running.
$env:API_ALLOW_WRITES = '1'
npm test
npm run report

Write scenarios require API_ALLOW_WRITES=1. Email scenarios additionally require API_ALLOW_EMAILS=1 and API_TEST_EMAIL. PDF checks run by default; set API_TEST_PDF=0 if the converter is unavailable. Set API_IGNORE_HTTPS_ERRORS=1 only when testing local self-signed certificates. See the TypeScript API test guide for configuration, individual scenarios, cleanup, and reports.

Web UI end-to-end tests

The shared scenarios support angular, reactjs, vuejs, nextjs, bff-reactjs, blazor-server, and blazor-wasm. Install the selected UI's dependencies and configure its backend/Identity Server URLs first. React and Next.js share a default port; BFF React also uses port 3000 for its frontend and shares browser port 44348 with Blazor WebAssembly, so run conflicting applications separately.

For TypeScript Playwright:

cd src/e2e/ui/node/playwright
npm ci
npx playwright install chromium
Copy-Item .env.example .env # First-time setup; enter credentials and URLs.
$env:E2E_APPS = 'reactjs' # Select one app or a comma-separated list.
$env:E2E_START_SERVERS = '1'
npm run test:headed -- --project=reactjs
npm run report

Headed desktop browsers open maximized. E2E_START_SERVERS=1 manages the selected UI servers; it does not start the API or Identity Server. Build the selected Blazor project first, as its managed start command uses --no-build. BFF React also requires its YARP proxy to be running. Use E2E_START_SERVERS=0 for servers you start yourself. See the TypeScript Playwright guide for application-specific setup and test selection.

For .NET Playwright and Selenium, start the selected UI yourself and use the .NET 10 SDK (plus Chrome for Selenium):

Copy-Item src/e2e/ui/dotnet/.env.example src/e2e/ui/dotnet/.env
# Enter credentials and URLs in the ignored .env file.
$env:E2E_ENV_FILE = (Resolve-Path src/e2e/ui/dotnet/.env).Path
$env:E2E_APPS = 'reactjs'
dotnet build src/e2e/ui/dotnet/Playwright
powershell -File src/e2e/ui/dotnet/Playwright/bin/Debug/net10.0/playwright.ps1 install chromium
dotnet test src/e2e/ui/dotnet/Playwright --logger trx
dotnet test src/e2e/ui/dotnet/Selenium --logger trx

Both .NET runners use visible, maximized browsers by default; set E2E_HEADLESS=1 for headless runs. See the .NET UI test guide for filters and reports.

For both web UI suites, set E2E_ALLOW_WRITES=1 for CRUD and playground queue tests against a disposable backend, and E2E_PDF=1 for PDF export. Playground queue tests require Fake notification providers. Blazor fixture creation/cleanup also requires E2E_API_TOKEN. Local self-signed browser certificates can be handled with E2E_IGNORE_HTTPS_ERRORS=1; server-side certificate trust must be configured separately.

Mobile Android UI tests

Install the latest Flutter, Kotlin, React Native, MAUI, and Capacitor builds on one Android emulator/device and sign in to each app. Keep the API and Identity Server running, and start Metro on port 8081 for React Native debug builds. The runner tests installed apps; it does not rebuild them.

./src/Mobiles/tests/Run-UiTests.ps1 -App All -Feature Home
./src/Mobiles/tests/Run-UiTests.ps1 -App All -Feature Navigation
# Run every default feature, or select one app:
./src/Mobiles/tests/Run-UiTests.ps1 -App All
./src/Mobiles/tests/Run-UiTests.ps1 -App Flutter -Feature Home

See the mobile UI test guide for Android SDK/JDK setup, individual test methods, optional CRUD/PDF checks, and screenshots/reports. These UI Automator tests run on Android; they do not verify iOS.

Application URLs:

https://github.com/phongnguyend/Practical.CleanArchitecture/wiki/Application-URLs

Roadmap:

https://github.com/phongnguyend/Practical.CleanArchitecture/wiki/Roadmap

Licence 🔑

This repository is licensed under the MIT license.

Duende.IdentityServer License 🔑

Duende.IdentityServer is available under both a FOSS (RPL) and a commercial license.

For the production environment, it is necessary to get a specific license, if you would like more information about the licensing of Duende.IdentityServer - please check this link.

The source code under /src/IdentityServers/Duende folder uses the source code from https://github.com/DuendeSoftware/IdentityServer.Quickstart.UI which is under the terms of the following license.

استكشف مشاريع مشابهة ومرتبطة

جارٍ التحميل…