🏛️ Clean Architecture Template — .NET 11

Kurumsal düzeyde, üretime hazır bir .NET 11 Clean Architecture şablonu.
CQRS, DDD, Saga Pattern, Multi-Tenancy, Rate Limiting, OpenTelemetry ve modern DevOps araçlarını tam entegre içerir.
📐 Proje Yapısı
CleanArchitecture/
│
├── src/
│ │
│ ├── 🟣 CleanArchitecture.Domain
│ │ ├── Abstractions/
│ │ │ ├── Entity.cs ← Base entity (Id, CreatedAt, TenantId, DomainEvents)
│ │ │ ├── IDomainEvent.cs ← Domain event arayüzü
│ │ │ ├── DomainEvent.cs ← Base domain event record
│ │ │ ├── Result.cs ← Result<T> pattern
│ │ │ ├── Error.cs ← Hata tanımları
│ │ │ ├── IRepository.cs ← Generic repository arayüzü
│ │ │ └── IUnitOfWork.cs ← Unit of Work arayüzü
│ │ ├── Entities/
│ │ │ ├── Product.cs ← Domain entity + factory method
│ │ │ └── ProductCreatedDomainEvent.cs ← Domain event
│ │ └── Repositories/
│ │ └── IProductRepository.cs
│ │
│ ├── 🔵 CleanArchitecture.Application
│ │ ├── Abstractions/
│ │ │ ├── Cache/ICacheService.cs ← Redis cache sözleşmesi
│ │ │ ├── Messaging/ICommand.cs ← ICommand / IQuery tanımları
│ │ │ ├── Messaging/ICommandHandler.cs ← Handler arayüzleri
│ │ │ ├── Messaging/IEventBus.cs ← Event bus sözleşmesi
│ │ │ └── MultiTenancy/ITenantService.cs
│ │ ├── Behaviors/ ← AOP Pipeline Behaviors
│ │ │ ├── LoggingPipelineBehavior.cs ← Request/Response loglama
│ │ │ ├── ValidationPipelineBehavior.cs ← FluentValidation entegrasyonu
│ │ │ └── PerformancePipelineBehavior.cs← Yavaş istek tespiti (>500ms)
│ │ ├── Features/Products/
│ │ │ ├── Commands/CreateProduct/ ← Command + Handler + Validator
│ │ │ ├── Queries/GetAllProducts/ ← Query + Handler (Redis cache)
│ │ │ └── Queries/GetProductById/ ← Query + Handler
│ │ ├── Dtos/ProductDto.cs
│ │ ├── Mappings/ProductMappingProfile.cs ← AutoMapper profili
│ │ └── DependencyInjection.cs
│ │
│ ├── 🟡 CleanArchitecture.Infrastructure
│ │ ├── Persistence/
│ │ │ ├── AppDbContext.cs ← EF Core + Domain Event dispatch + IUnitOfWork
│ │ │ └── Configurations/ ← IEntityTypeConfiguration
│ │ ├── Repositories/
│ │ │ ├── Repository.cs ← Generic repository implementasyonu
│ │ │ └── ProductRepository.cs
│ │ ├── Cache/
│ │ │ └── RedisCacheService.cs ← StackExchange.Redis implementasyonu
│ │ ├── Messaging/
│ │ │ ├── EventBus.cs ← MassTransit IEventBus implementasyonu
│ │ │ ├── Consumers/ProductCreatedConsumer.cs
│ │ │ └── Sagas/
│ │ │ ├── OrderState.cs ← Saga state
│ │ │ ├── OrderMessages.cs ← Saga mesajları
│ │ │ └── OrderStateMachine.cs ← MassTransit Saga State Machine
│ │ ├── MultiTenancy/TenantService.cs ← X-Tenant-Id header okuma
│ │ └── DependencyInjection.cs
│ │
│ └── 🟢 CleanArchitecture.WebAPI
│ ├── Controllers/ProductsController.cs ← REST API endpoints
│ ├── Middleware/GlobalExceptionHandler.cs ← IExceptionHandler
│ ├── Program.cs ← Tüm servis kayıtları + Pipeline
│ └── appsettings.json
│
├── tests/
│ └── 🧪 CleanArchitecture.Tests
│ ├── Application/Products/ ← Command handler testleri
│ └── Domain/Entities/ ← Domain logic testleri
│
├── k6/
│ └── load-test.js ← K6 yük testi senaryosu
│
├── docker/
│ └── prometheus/prometheus.yml
│
├── .github/
│ └── workflows/ci-cd.yml ← GitHub Actions CI/CD
│
├── docker-compose.yml ← Tüm servisler
├── Dockerfile
├── SonarQube.Analysis.xml
└── README.md
🧱 Mimari Prensipler & Desenler
| # |
Desen / Prensip |
Açıklama |
| 1 |
Clean Architecture |
Domain → Application → Infrastructure → WebAPI katman bağımlılık yönü |
| 2 |
SOLID |
Tek sorumluluk, açık/kapalı, Liskov, arayüz ayrımı, bağımlılık tersine çevirme |
| 3 |
DDD |
Entity, Aggregate Root, DomainEvent, Repository, Value Object |
| 4 |
CQRS |
ICommand<T> ve IQuery<T> ayrımı, MediatR ile dispatch |
| 5 |
Saga Pattern |
MassTransitStateMachine — sipariş iş akışı yönetimi |
| 6 |
Result Pattern |
Result<T> + Error — exception-free hata yönetimi |
| 7 |
Unit of Work |
IUnitOfWork → AppDbContext — atomik veritabanı işlemleri |
| 8 |
Repository Pattern |
Generic IRepository<T> + domain-specific repository |
| 9 |
AOP |
MediatR Pipeline Behavior: Logging, Validation, Performance |
| 10 |
Multi-Tenancy |
X-Tenant-Id header + EF Core global query filter |
| 11 |
OOP |
Encapsulation, Inheritance, Polymorphism — tüm katmanlarda |
🛠️ Teknoloji Stack'i
⚙️ Core Framework
| Paket |
Versiyon |
Kullanım |
| .NET |
11.0 |
Target framework |
| C# |
14.0 |
Primary constructors, collection expressions |
| MediatR |
12.4 |
CQRS mediator |
| FluentValidation |
11.x |
Command/Query doğrulama |
| AutoMapper |
13.x |
Entity ↔ DTO dönüşümleri |
🗄️ Veri Katmanı
| Paket |
Versiyon |
Kullanım |
| EF Core |
9.x |
ORM, Code-First, Migrations |
| SQL Server |
— |
Ana veritabanı |
| StackExchange.Redis |
— |
Distributed cache |
📨 Mesajlaşma & Event
| Paket |
Versiyon |
Kullanım |
| MassTransit |
8.4 |
Message bus abstraction |
| RabbitMQ |
— |
Message broker |
| Saga State Machine |
— |
Uzun süreçli iş akışları |
🔐 Güvenlik
| Paket |
Kullanım |
| JWT Bearer (OAuth) |
Kimlik doğrulama ve yetkilendirme |
| Rate Limiting |
Fixed Window — 100 istek/dakika, 429 Too Many Requests |
📊 Gözlemlenebilirlik
| Araç |
URL |
Kullanım |
| Serilog |
— |
Structured logging (Console + File + Seq) |
| OpenTelemetry |
— |
Distributed tracing + metrics |
| Prometheus |
:9090 |
Metrics scraping (/metrics) |
| Grafana |
:3000 |
Dashboard görselleştirme |
| Seq |
:8080 |
Log UI |
| Health Checks |
/health |
SQL Server + Redis sağlık kontrolü |
🐳 DevOps
| Araç |
Kullanım |
| Docker |
Uygulama konteynerleştirme |
| Docker Compose |
Multi-container orkestrasyon |
| GitHub Actions |
CI/CD pipeline (build → test → sonar → docker push) |
| SonarQube |
Statik kod analizi ve güvenlik taraması |
| K6 |
Yük ve performans testi |
🧪 Test
| Paket |
Kullanım |
| xUnit |
Unit test framework |
| NSubstitute |
Mock / Stub |
| FluentAssertions |
Okunabilir assertion |
📦 NuGet Template Olarak Kullanım
Bu proje bir dotnet new template'i olarak paketlenmiştir.
🔧 Kurulum
# NuGet'ten kur (yayınlandıktan sonra)
dotnet new install AliCanYucel.CleanArchitecture.Template
# Veya yerel .nupkg'dan kur
dotnet new install ./nupkg/AliCanYucel.CleanArchitecture.Template.1.0.0.nupkg
🚀 Yeni Proje Oluştur
# Tüm özelliklerle
dotnet new cleanarch --name MyProject
# Opsiyonlarla
dotnet new cleanarch --name MyProject --IncludeDocker true --IncludeTests true --IncludeK6 false --IncludeCICD true
# Önizleme (dosya oluşturmaz)
dotnet new cleanarch --name MyProject --dry-run
⚙️ Template Parametreleri
| Parametre |
Tip |
Varsayılan |
Açıklama |
--name |
string |
MyProject |
Proje adı (tüm namespace'lere yansır) |
--IncludeDocker |
bool |
true |
Dockerfile + docker-compose.yml |
--IncludeTests |
bool |
true |
xUnit test projesi |
--IncludeK6 |
bool |
true |
K6 yük testi scriptleri |
--IncludeCICD |
bool |
true |
GitHub Actions CI/CD pipeline |
🔄 Template'i Kaldır
dotnet new uninstall AliCanYucel.CleanArchitecture.Template
📦 Yeniden Paketleme
dotnet pack CleanArchitecture.Template.csproj --no-build -o nupkg
🐳 Docker ile (Önerilen)
# Tüm servisleri ayağa kaldır
docker-compose up -d
🖥️ Manuel
dotnet restore
dotnet run --project src/CleanArchitecture.WebAPI
Servis URL'leri
| Servis |
URL |
| API |
http://localhost:5000 |
| OpenAPI |
http://localhost:5000/openapi |
| Health Check |
http://localhost:5000/health |
| Prometheus Metrics |
http://localhost:5000/metrics |
| Prometheus UI |
http://localhost:9090 |
| Grafana |
http://localhost:3000 admin / admin |
| RabbitMQ |
http://localhost:15672 guest / guest |
| Seq |
http://localhost:8080 |
🧪 Testler
# Unit testleri çalıştır
dotnet test
# Kod kapsama raporu
dotnet test --collect:"XPlat Code Coverage"
# K6 yük testi
k6 run k6/load-test.js
# Özel URL ile K6
k6 run -e BASE_URL=http://localhost:5000 k6/load-test.js
📡 API Örnekleri
### Tüm ürünleri getir
GET /api/products
X-Tenant-Id: tenant-1
### Tekil ürün
GET /api/products/{id}
X-Tenant-Id: tenant-1
### Yeni ürün oluştur
POST /api/products
Content-Type: application/json
X-Tenant-Id: tenant-1
{
"name": "Laptop",
"description": "Gaming laptop",
"price": 1500.00,
"stock": 10
}
🔄 Saga Akışı (Order State Machine)
[İlk]
│
▼ OrderSubmitted
[Submitted]
├──▶ OrderApproved ──▶ [Approved]
│ │
│ ▼ OrderCompleted
│ [Completed] ✅
│
└──▶ OrderRejected ──▶ [Rejected] ❌
⚙️ CI/CD Pipeline
push → main/develop
├── dotnet restore
├── dotnet build
├── dotnet test + coverage
├── SonarQube analizi
└── Docker build + push (sadece main)
🌐 Multi-Tenancy
Her API isteğinde X-Tenant-Id header'ı gönderilir.
TenantService bu değeri okur, AppDbContext EF Core global query filter ile veriyi otomatik izole eder.
"TenantSettings": {
"Tenants": [
{ "Id": "tenant-1", "Name": "Şirket A" },
{ "Id": "tenant-2", "Name": "Şirket B" }
]
}
🔒 AOP Pipeline (Aspect-Oriented)
Request
│
▼ LoggingPipelineBehavior ← İstek başlangıç/bitiş loglar
│
▼ PerformancePipelineBehavior ← 500ms üzeri istekleri uyarır
│
▼ ValidationPipelineBehavior ← FluentValidation çalıştırır
│
▼ CommandHandler / QueryHandler ← İş mantığı
Bu proje Ali Can Yücel tarafından yapılmıştır.