Orchestrates use cases và business workflows. Định nghĩa "what" the system does.
Application/
├── Common/ # 🔗 Shared Components
│ ├── ICommand.cs # Command interfaces (CQRS)
│ ├── ICommandHandler.cs # Command handler interfaces
│ ├── IQuery.cs # Query interfaces (CQRS)
│ ├── IQueryHandler.cs # Query handler interfaces
│ ├── IDomainEventHandler.cs # Domain event handler interface
│ ├── IDomainEventDispatcher.cs # Domain event dispatcher
│ │
│ ├── Behaviors/ # 🔄 MediatR Pipeline Behaviors
│ │ ├── ValidationBehavior.cs # Validate requests
│ │ ├── LoggingBehavior.cs # Log all requests/responses
│ │ ├── PerformanceBehavior.cs # Monitor performance
│ │ ├── AuthorizationBehavior.cs # Check permissions
│ │ ├── CachingBehavior.cs # Cache responses
│ │ ├── TransactionBehavior.cs # Database transactions
│ │ └── DomainEventBehavior.cs # Dispatch domain events
│ │
│ ├── Exceptions/ # 🚨 Custom Exceptions
│ │ ├── ApplicationException.cs # Base application exception
│ │ ├── ValidationException.cs # Validation errors
│ │ ├── NotFoundException.cs # Entity not found
│ │ ├── UnauthorizedException.cs # Auth failures
│ │ ├── ForbiddenException.cs # Permission denied
│ │ ├── ConflictException.cs # Business conflicts
│ │ ├── BusinessRuleException.cs # Business rule violations
│ │ └── ExternalServiceException.cs # External service errors
│ │
│ └── Models/ # 📋 Shared Models
│ ├── PaginatedResult.cs # Paginated responses
│ ├── PaginationRequest.cs # Pagination parameters
│ ├── AuditableEntity.cs # Base auditable entity
│ └── SortOrder.cs # Sorting directions
│
├── Features/ # 🎯 Feature-based Organization (Vertical Slices)
│ ├── Auth/ # Authentication features
│ │ ├── Login/
│ │ │ ├── LoginCommand.cs # Login command
│ │ │ ├── LoginCommandHandler.cs # Login logic
│ │ │ └── LoginCommandValidator.cs # Login validation
│ │ ├── Logout/
│ │ ├── GetProfile/
│ │ ├── ChangePassword/
│ │ └── RefreshToken/
│ │
│ ├── User/ # User management features
│ │ ├── CreateUser/
│ │ │ ├── CreateUserCommand.cs
│ │ │ ├── CreateUserCommandHandler.cs
│ │ │ └── CreateUserCommandValidator.cs
│ │ ├── GetUsers/
│ │ ├── UpdateUserProfile/
│ │ └── DeleteUser/
│ │
│ └── Conversation/ # Conversation features
│ ├── CreateConversation/
│ ├── GetConversations/
│ ├── SendMessage/
│ ├── GetMessages/
│ └── DeleteConversation/
│
├── EventHandlers/ # 📢 Domain Event Handlers
│ ├── UserCreatedEventHandler.cs # Handle user creation
│ ├── UserUpdatedEventHandler.cs # Handle user updates
│ └── UserDeactivatedEventHandler.cs # Handle user deactivation
│
└── Interfaces/ # 🔌 External Service Interfaces (DIP)
├── IUserRepository.cs # User data access
├── IPasswordHasher.cs # Password hashing service
└── ITokenService.cs # JWT token service
Tổ chức theo features thay vì technical layers
Ưu điểm:
- ✅ High Cohesion - Mọi thứ liên quan đến 1 feature ở cùng chỗ
- ✅ Easy to Find - Dễ tìm code liên quan đến use case
- ✅ Team Productivity - Team có thể work parallel trên các features
- ✅ Maintainable - Thay đổi feature không ảnh hưởng features khác
Structure mỗi feature:
FeatureName/
├── Command.cs # Input model
├── CommandHandler.cs # Business logic
├── CommandValidator.cs # Input validation
└── Response.cs # Output model
Pipeline behaviors chạy trước/sau mọi request
Thứ tự quan trọng:
- Logging - Log request đầu vào
- Performance - Đo thời gian execution
- Authorization - Check permissions
- Validation - Validate input
- Caching - Cache responses (cho queries)
- Transaction - Database transactions (cho commands)
- DomainEvent - Dispatch domain events
Structured exception hierarchy cho error handling
- ApplicationException - Base cho tất cả app exceptions
- ValidationException - Input validation errors
- BusinessRuleException - Business logic violations
- External exceptions - Integration failures
Handle domain events để thực hiện side effects
Ví dụ UserCreatedEvent:
- Send welcome email
- Create default user profile
- Initialize user settings
- Track analytics
Define contracts cho external services
Implemented by Infrastructure layer:
- Database repositories
- External APIs
- File storage
- Email services
- Caching services
public record CreateUserCommand : ICommand<Result<CreateUserResponse>>
{
public string Email { get; init; }
public string FullName { get; init; }
public string Password { get; init; }
}public record GetUsersQuery : IQuery<PaginatedResult<UserDto>>
{
public int Page { get; init; } = 1;
public int PageSize { get; init; } = 10;
}- ❌ No Infrastructure concerns - Không có EF, SQL, HTTP
- ❌ No UI logic - Không có presentation logic
- ❌ No external dependencies - Chỉ abstractions/interfaces
- ❌ No business rules - Business logic thuộc về Domain
- ✅ Orchestrate use cases - Coordinate business workflows
- ✅ Define interfaces - Contracts cho external services
- ✅ Handle domain events - Side effects từ domain events
- ✅ Validate inputs - Input validation với FluentValidation
- ✅ Transform data - Map giữa domain objects và DTOs
- Domain Layer - Core business logic
- MediatR - CQRS và mediator pattern
- FluentValidation - Input validation
- Microsoft.Extensions.* - Abstractions (Logging, Caching)
- Thin Handlers - Logic minimal, delegate to domain
- Validation First - Validate inputs trước khi process
- Error Handling - Consistent exception handling
- Event-Driven - Use domain events cho side effects
- Testable - Easy to unit test handlers