System Architecture
Clean Architecture with Domain-Driven Design Principles
Architecture Overview
The Shirinzad E-Commerce Platform is built using Clean Architecture principles combined with Domain-Driven Design (DDD), powered by the ABP.io Framework 9.3.5 and .NET 9.0.
Key Principle: The architecture ensures separation of concerns, testability, and maintainability through clear layer boundaries and dependency rules.
Core Benefits
- Independent of frameworks and UI
- Testable business logic
- Independent of database
- Easy to maintain and extend
- Clear separation of concerns
- Scalable and flexible
High-Level Architecture
graph TB
subgraph Presentation[Presentation Layer]
API[HTTP API Controllers]
Web[Web UI - Razor Pages]
Swagger[Swagger/OpenAPI]
end
subgraph Application[Application Layer]
Services[Application Services]
DTOs[DTOs & Mapping]
Validators[Input Validators]
Interfaces[Service Interfaces]
end
subgraph Domain[Domain Layer]
Entities[Domain Entities]
DomainServices[Domain Services]
Repos[Repository Interfaces]
Events[Domain Events]
ValueObjects[Value Objects]
end
subgraph Infrastructure[Infrastructure Layer]
EFCore[EF Core - Data Access]
Repos2[Repository Implementations]
Redis[Redis Caching]
Email[Email Service]
Files[File Storage]
External[External Integrations]
end
subgraph Database[Data Storage]
SQL[(SQL Server)]
Cache[(Redis Cache)]
FileSystem[(File System)]
end
API --> Services
Web --> Services
Swagger --> API
Services --> DTOs
Services --> Validators
Services --> Interfaces
Services --> DomainServices
DomainServices --> Entities
Entities --> ValueObjects
Services --> Repos
Repos --> Repos2
Repos2 --> EFCore
EFCore --> SQL
Services --> Redis
Services --> Email
Services --> Files
Redis --> Cache
Files --> FileSystem
External --> SQL
Layered Architecture with Dependency Rule: Outer layers depend on inner layers
Architecture Layers
1. Presentation Layer
Projects: Shirinzad.Shop.Web, Shirinzad.Shop.HttpApi
Responsibilities:
- HTTP API endpoints (RESTful)
- Request/response handling
- Authentication & authorization middleware
- Web UI (Razor Pages)
- API documentation (Swagger)
- Input validation (first layer)
Key Features:
- 110+ API endpoints
- JWT Bearer authentication
- Swagger UI for API testing
- Response compression (Brotli/Gzip)
- CORS configuration
- Rate limiting support
// Example Controller
[ApiController]
[Route("api/app/product")]
[Authorize]
public class ProductController : ShopController
{
private readonly IProductAppService _productService;
[HttpGet]
public Task<PagedResultDto<ProductDto>> GetListAsync(
PagedAndSortedResultRequestDto input)
{
return _productService.GetListAsync(input);
}
}
2. Application Layer
Projects: Shirinzad.Shop.Application, Shirinzad.Shop.Application.Contracts
Responsibilities:
- Orchestrate domain logic
- Implement use cases
- DTO mapping (AutoMapper)
- Transaction management
- Cross-cutting concerns (caching, logging)
- Permission checking
Key Components:
| Component | Count | Purpose |
|---|---|---|
| Application Services | 32+ | Business operations |
| DTOs | 120+ | Data transfer |
| AutoMapper Profiles | 10+ | Entity-DTO mapping |
| Validators | 50+ | Input validation |
// Example Application Service
public class ProductAppService : ShopAppService, IProductAppService
{
private readonly IRepository<Product, Guid> _productRepository;
private readonly CacheService _cacheService;
public async Task<ProductDto> CreateAsync(CreateProductDto input)
{
// Validate
await ValidateProductAsync(input);
// Create entity
var product = new Product(
GuidGenerator.Create(),
input.Name,
input.Slug,
input.Price
);
// Save to database
await _productRepository.InsertAsync(product);
// Invalidate cache
await _cacheService.RemoveAsync(CacheKeys.FeaturedProductsKey);
// Return DTO
return ObjectMapper.Map<Product, ProductDto>(product);
}
}
3. Domain Layer (Core)
Projects: Shirinzad.Shop.Domain, Shirinzad.Shop.Domain.Shared
Responsibilities:
- Business logic and rules
- Domain entities
- Domain services
- Repository interfaces
- Domain events
- Value objects
Domain Entities:
Product Catalog
- Product
- ProductVariant
- ProductSpec
- ProductGallery
- Category
- Brand
- Tag
Orders & Payments
- Cart
- CartItem
- Order
- OrderItem
- OrderStatusHistory
- Payment
- PaymentMethod
- Discount
User & Content
- UserProfile
- UserAddress
- ProductReview
- Wishlist
- Notification
- FileUpload
- AuditLog
Total: 55+ domain entities with rich business logic
// Example Domain Entity with Business Logic
public class Product : FullAuditedAggregateRoot<Guid>
{
public string Name { get; private set; }
public decimal Price { get; private set; }
public int StockQuantity { get; private set; }
// Business method - encapsulates logic
public void DecreaseStock(int quantity)
{
if (quantity <= 0)
throw new BusinessException("Quantity must be positive");
if (StockQuantity < quantity)
throw new BusinessException("Insufficient stock");
StockQuantity -= quantity;
}
// Business rule
public bool IsInStock() => StockQuantity > 0;
// Calculated property
public decimal GetEffectivePrice()
{
return DiscountPrice.HasValue && DiscountPrice > 0
? DiscountPrice.Value
: Price;
}
}
4. Infrastructure Layer
Projects: Shirinzad.Shop.EntityFrameworkCore
Responsibilities:
- Database access (EF Core)
- Repository implementations
- External service integrations
- Caching implementations
- File storage
- Email sending
Key Features:
| Feature | Technology | Details |
|---|---|---|
| Database | EF Core 9.0 | 58 tables, 46+ indexes |
| Migrations | Code-First | 20 migrations |
| Caching | Redis | Distributed caching |
| File Storage | Local/Cloud | Blob storage ready |
// Example DbContext Configuration
public class ShopDbContext : AbpDbContext<ShopDbContext>
{
public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Product>(b =>
{
b.ToTable("AppProducts");
b.HasIndex(x => x.Slug).IsUnique();
b.HasIndex(x => x.IsActive);
b.HasIndex(x => x.IsFeatured);
b.Property(x => x.Price).HasPrecision(18, 2);
});
}
}
Project Structure
Shirinzad.Shop/
├── src/
│ ├── Shirinzad.Shop.Domain.Shared/ # Shared constants, enums
│ ├── Shirinzad.Shop.Domain/ # Domain entities & logic
│ ├── Shirinzad.Shop.Application.Contracts/ # Service interfaces & DTOs
│ ├── Shirinzad.Shop.Application/ # Application services
│ ├── Shirinzad.Shop.EntityFrameworkCore/ # EF Core, repositories
│ ├── Shirinzad.Shop.HttpApi/ # API controllers
│ ├── Shirinzad.Shop.HttpApi.Client/ # HTTP client proxies
│ └── Shirinzad.Shop.Web/ # Web host & UI
├── test/
│ ├── Shirinzad.Shop.Application.Tests/ # Application tests
│ ├── Shirinzad.Shop.Domain.Tests/ # Domain tests
│ ├── Shirinzad.Shop.EntityFrameworkCore.Tests/ # EF Core tests
│ └── Shirinzad.Shop.TestBase/ # Test utilities
└── docs/ # Documentation
Project Dependencies
graph LR
Web[Web] --> HttpApi
Web --> Application
HttpApi --> Application.Contracts
Application --> Application.Contracts
Application --> Domain
Application --> EFCore
Domain --> Domain.Shared
EFCore --> Domain
Application.Contracts --> Domain.Shared
Technology Stack
Backend Technologies
| .NET | 9.0 |
| ABP Framework | 9.3.5 |
| EF Core | 9.0 |
| C# | 13.0 |
| AutoMapper | Latest |
Infrastructure
| SQL Server | 2019+ |
| Redis | Latest |
| Docker | Supported |
| Nginx | Reverse Proxy |
| Serilog | Logging |
Design Patterns & Principles
Architectural Patterns
- Clean Architecture
- Domain-Driven Design (DDD)
- Repository Pattern
- Unit of Work Pattern
- CQRS Principles
- Dependency Injection
SOLID Principles
- Single Responsibility
- Open/Closed
- Liskov Substitution
- Interface Segregation
- Dependency Inversion
Design Patterns
- Factory Pattern
- Strategy Pattern
- Decorator Pattern
- Observer Pattern (Events)
- Specification Pattern
- Null Object Pattern
Best Practices
- Async/Await throughout
- Immutable value objects
- Rich domain models
- Explicit dependencies
- Fail-fast validation
- Logging & monitoring
Request/Response Flow
sequenceDiagram
participant C as Client
participant API as API Controller
participant AS as Application Service
participant DS as Domain Service
participant E as Entity
participant R as Repository
participant DB as Database
participant Cache as Redis Cache
C->>API: HTTP Request
API->>API: Authentication
API->>API: Authorization
API->>AS: Call Service Method
AS->>Cache: Check Cache
alt Cache Hit
Cache-->>AS: Return Cached Data
AS-->>API: Return DTO
else Cache Miss
AS->>R: Query Repository
R->>DB: Execute SQL
DB-->>R: Return Entity
R-->>AS: Return Entity
AS->>DS: Business Logic
DS->>E: Domain Operations
E-->>DS: Updated Entity
DS-->>AS: Result
AS->>Cache: Store in Cache
AS-->>API: Return DTO
end
API-->>C: HTTP Response
Scalability & Performance
Horizontal Scaling
The platform is designed for horizontal scaling across multiple servers:
- Stateless application design
- Distributed caching with Redis
- Database connection pooling
- Load balancer ready
- Session state in Redis
- Shared file storage support
Performance Optimizations
| Optimization | Implementation | Impact |
|---|---|---|
| Database Indexes | 46+ strategic indexes | Query speed: 50-90% faster |
| Redis Caching | 30+ cache patterns | Response time: 80-95% faster |
| Response Compression | Brotli/Gzip | Bandwidth: 60-80% reduction |
| Query Optimization | Projections, AsNoTracking | Memory: 40-60% reduction |
| Connection Pooling | Min: 1, Max: 20 | Connection overhead reduced |
Security Architecture
Authentication
- JWT Bearer Tokens: Stateless authentication
- Token Expiration: Configurable (default 1 hour)
- Refresh Tokens: Extended sessions
- Password Hashing: BCrypt/PBKDF2
Authorization
- Role-Based: Admin, Customer
- Permission-Based: Fine-grained control
- Policy-Based: Complex scenarios
- Resource-Based: Owner validation
Data Protection
- Input Validation: All DTOs validated
- SQL Injection: EF Core parameterization
- XSS Protection: Output encoding
- CSRF Protection: Anti-forgery tokens
Monitoring
- Audit Logging: All actions tracked
- Rate Limiting: DDoS protection
- Health Checks: System monitoring
- Exception Logging: Serilog integration
ABP Framework Features Used
Module System
- Modular architecture
- Dependency management
- Plugin support
Domain Layer
- Entities & Aggregates
- Repositories
- Domain Services
- Specifications
Application Layer
- Application Services
- DTOs & AutoMapper
- Validation
- Authorization
Infrastructure
- EF Core integration
- Multi-tenancy
- Background Jobs
- Event Bus
Cross-Cutting
- Auditing
- Caching
- Exception Handling
- Localization
Testing
- In-Memory Database
- Test Base Classes
- Mocking Support