Skip to content

Latest commit

 

History

History
188 lines (162 loc) · 7.24 KB

File metadata and controls

188 lines (162 loc) · 7.24 KB

🔧 Application Layer

Orchestrates use cases và business workflows. Định nghĩa "what" the system does.

📁 Cấu trúc Folders

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

🎯 Mục đích từng folder

🎯 Features/ - Vertical Slices

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

🔄 Behaviors/ - Cross-cutting Concerns

Pipeline behaviors chạy trước/sau mọi request

Thứ tự quan trọng:

  1. Logging - Log request đầu vào
  2. Performance - Đo thời gian execution
  3. Authorization - Check permissions
  4. Validation - Validate input
  5. Caching - Cache responses (cho queries)
  6. Transaction - Database transactions (cho commands)
  7. DomainEvent - Dispatch domain events

🚨 Exceptions/ - Error Handling

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

📢 EventHandlers/ - Side Effects

Handle domain events để thực hiện side effects

Ví dụ UserCreatedEvent:

  • Send welcome email
  • Create default user profile
  • Initialize user settings
  • Track analytics

🔌 Interfaces/ - Dependency Inversion

Define contracts cho external services

Implemented by Infrastructure layer:

  • Database repositories
  • External APIs
  • File storage
  • Email services
  • Caching services

🔄 CQRS Pattern

Commands (Write Operations)

public record CreateUserCommand : ICommand<Result<CreateUserResponse>>
{
    public string Email { get; init; }
    public string FullName { get; init; }
    public string Password { get; init; }
}

Queries (Read Operations)

public record GetUsersQuery : IQuery<PaginatedResult<UserDto>>
{
    public int Page { get; init; } = 1;
    public int PageSize { get; init; } = 10;
}

🚫 Điều KHÔNG ĐƯỢC làm

  • 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

✅ Điều NÊN làm

  • 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

🔗 Dependencies

  • Domain Layer - Core business logic
  • MediatR - CQRS và mediator pattern
  • FluentValidation - Input validation
  • Microsoft.Extensions.* - Abstractions (Logging, Caching)

💡 Best Practices

  1. Thin Handlers - Logic minimal, delegate to domain
  2. Validation First - Validate inputs trước khi process
  3. Error Handling - Consistent exception handling
  4. Event-Driven - Use domain events cho side effects
  5. Testable - Easy to unit test handlers