application
Convenciones de la capa de aplicacion: casos de uso, CQRS, DTOs, validadores y mapeos.
Ficha técnica
| user-invocable | false |
|---|
Activación
Se carga sola al tocar ficheros que casan con sus rutas (paths:). No entra en el listado de skills.
paths:
- "**/Application/**/*.cs"
- "**/UseCases/**/*.cs"
- "**/Features/**/*.cs"
- "**/Commands/**/*.cs"
- "**/Queries/**/*.cs"
- "**/Handlers/**/*.cs"
- "**/DTOs/**/*.cs"
- "**/Validators/**/*.cs"
- "**/Behaviours/**/*.cs"
- "**/Mappings/**/*.cs"
- "**/Services/**/*Service.cs"
- "**/*Command.cs"
- "**/*Query.cs"
- "**/*Handler.cs"
- "**/*Dto.cs"
- "**/*DTO.cs"
- "**/*Validator.cs"
- "**/*Behaviour.cs"
- "**/*Behavior.cs"Ficheros del pack 0
Solo SKILL.md.
Contenido
Se carga por ruta, no por invocacion: el campo
paths:la activa cuando Claude trabaja con ficheros que casan con esos patrones. No aparece en el menu (user-invocable: false) y no ocupa contexto mientras no case ningun fichero.Procede de
.claude/skills/application/SKILL.md. Se convirtio en skill porque un plugin no distribuyerules/.
Reglas para Capa de Aplicación
Este archivo aplica cuando Claude trabaja con casos de uso, comandos, queries, DTOs y servicios de aplicación. La capa Application orquesta el dominio pero no contiene lógica de negocio.
⚠️ AVISO IMPORTANTE: MediatR → Mediator
A partir de 2026, recomendamos usar Mediator (martinothamar) en lugar de MediatR:
| Aspecto | MediatR v13+ | Mediator |
|---|---|---|
| Licencia | Comercial ($500-2000/año) | MIT (gratuito) |
| Rendimiento | Reflexión runtime | Source generators (más rápido) |
| API | IRequest, IRequestHandler | IRequest, IRequestHandler (compatible) |
| Pipeline Behaviors | IPipelineBehavior | IPipelineBehavior (idéntico) |
Los ejemplos en este archivo usan la interfaz estándar (IRequest, IRequestHandler, IPipelineBehavior) que es compatible con ambas librerías.
⚠️ AVISO IMPORTANTE: AutoMapper → Mapperly
Misma trampa que MediatR: AutoMapper es comercial desde la v15 (licencia dual RPL-1.5 o comercial). El pin a 13.* la esquivaba por accidente, no por política.
| Aspecto | AutoMapper v15+ | Mapperly |
|---|---|---|
| Licencia | Comercial (dual RPL-1.5) | MIT (gratuito) |
| Rendimiento | Reflexión en tiempo de ejecución | Source generator (código generado, sin reflexión) |
| Trimming y AOT | Los rompe | Compatibles |
| Errores de mapeo | En tiempo de ejecución | En compilación |
| API | IMapper.Map<TDto>(entity) | método generado: mapper.ToDto(entity) |
Código nuevo: Mapperly. Es lo que emiten las plantillas de generador-crud. Si el proyecto ya usa AutoMapper, no hay que migrarlo por esto: fijar el rango cerrado [13.0.0,15.0.0) para no entrar en la versión comercial en un dotnet restore, y anotar la migración en _hilo/DEUDA_TECNICA.md.
📚 Ver
_patron/01_Estructura_Tecnica/GUIA_ARQUITECTURA.mdpara guía de migración y detalles completos.
PRINCIPIOS FUNDAMENTALES
| Principio | Descripción |
|---|---|
| Orquestación | Coordina el dominio, no implementa lógica de negocio |
| CQRS | Separar Commands (escritura) de Queries (lectura) |
| Independencia | Sin dependencias de Infrastructure o Presentation |
| Validación | Validar inputs antes de llegar al dominio |
PARTE 1: ESTRUCTURA DE CARPETAS
Organización por Features (Recomendada)
Application/
├── Common/
│ ├── Interfaces/
│ │ ├── IUnitOfWork.cs
│ │ ├── ICurrentUserService.cs
│ │ └── IDateTime.cs
│ ├── Behaviours/
│ │ ├── ValidationBehaviour.cs
│ │ ├── LoggingBehaviour.cs
│ │ └── PerformanceBehaviour.cs
│ ├── Exceptions/
│ │ ├── ValidationException.cs
│ │ ├── NotFoundException.cs
│ │ └── ForbiddenAccessException.cs
│ └── Mappings/
│ └── MappingProfile.cs
│
├── Features/
│ ├── Users/
│ │ ├── Commands/
│ │ │ ├── CreateUser/
│ │ │ │ ├── CreateUserCommand.cs
│ │ │ │ ├── CreateUserCommandHandler.cs
│ │ │ │ └── CreateUserCommandValidator.cs
│ │ │ └── UpdateUser/
│ │ │ └── ...
│ │ ├── Queries/
│ │ │ ├── GetUserById/
│ │ │ │ ├── GetUserByIdQuery.cs
│ │ │ │ ├── GetUserByIdQueryHandler.cs
│ │ │ │ └── UserDto.cs
│ │ │ └── GetAllUsers/
│ │ │ └── ...
│ │ └── EventHandlers/
│ │ └── UserCreatedEventHandler.cs
│ │
│ └── Orders/
│ ├── Commands/
│ ├── Queries/
│ └── EventHandlers/
│
└── DependencyInjection.cs
PARTE 2: COMMANDS (CQRS - Escritura)
Estructura de un Command
// CreateUserCommand.cs
namespace MyApp.Application.Features.Users.Commands.CreateUser;
public record CreateUserCommand : IRequest<Guid>
{
public required string Email { get; init; }
public required string FirstName { get; init; }
public required string LastName { get; init; }
public string? PhoneNumber { get; init; }
}
Handler del Command
// CreateUserCommandHandler.cs
namespace MyApp.Application.Features.Users.Commands.CreateUser;
public class CreateUserCommandHandler : IRequestHandler<CreateUserCommand, Guid>
{
private readonly IUserRepository _userRepository;
private readonly IUnitOfWork _unitOfWork;
public CreateUserCommandHandler(
IUserRepository userRepository,
IUnitOfWork unitOfWork)
{
_userRepository = userRepository;
_unitOfWork = unitOfWork;
}
public async Task<Guid> Handle(
CreateUserCommand request,
CancellationToken cancellationToken)
{
// 1. Crear entidad de dominio
var email = Email.Create(request.Email);
var user = User.Create(email, request.FirstName, request.LastName);
// 2. Persistir
await _userRepository.AddAsync(user, cancellationToken);
await _unitOfWork.SaveChangesAsync(cancellationToken);
// 3. Retornar ID
return user.Id;
}
}
Validator del Command (FluentValidation)
// CreateUserCommandValidator.cs
namespace MyApp.Application.Features.Users.Commands.CreateUser;
public class CreateUserCommandValidator : AbstractValidator<CreateUserCommand>
{
private readonly IUserRepository _userRepository;
public CreateUserCommandValidator(IUserRepository userRepository)
{
_userRepository = userRepository;
RuleFor(x => x.Email)
.NotEmpty().WithMessage("Email is required")
.EmailAddress().WithMessage("Email format is invalid")
.MustAsync(BeUniqueEmail).WithMessage("Email is already registered");
RuleFor(x => x.FirstName)
.NotEmpty().WithMessage("Name is required")
.MaximumLength(100).WithMessage("Name cannot exceed 100 characters");
RuleFor(x => x.LastName)
.NotEmpty().WithMessage("Last name is required")
.MaximumLength(100).WithMessage("Last name cannot exceed 100 characters");
}
private async Task<bool> BeUniqueEmail(
string email,
CancellationToken cancellationToken)
{
return !await _userRepository.ExistsByEmailAsync(email, cancellationToken);
}
}
PARTE 3: QUERIES (CQRS - Lectura)
Estructura de una Query
// GetUserByIdQuery.cs
namespace MyApp.Application.Features.Users.Queries.GetUserById;
public record GetUserByIdQuery(Guid Id) : IRequest<UserDto?>;
Handler de la Query
El handler habla con
I{Entity}Repository(métodos explícitos, paginación acotada) y nunca con elDbContextni con unIQueryable: el idioma de acceso a datos es uno y está eninfrastructure(ADR-034).
// GetUserByIdQueryHandler.cs
namespace MyApp.Application.Features.Users.Queries.GetUserById;
public class GetUserByIdQueryHandler : IRequestHandler<GetUserByIdQuery, UserDto?>
{
private readonly IUserRepository _userRepository;
private readonly IMapper _mapper;
public GetUserByIdQueryHandler(
IUserRepository userRepository,
IMapper mapper)
{
_userRepository = userRepository;
_mapper = mapper;
}
public async Task<UserDto?> Handle(
GetUserByIdQuery request,
CancellationToken cancellationToken)
{
var user = await _userRepository.GetByIdAsync(request.Id, cancellationToken);
return user is null ? null : _mapper.Map<UserDto>(user);
}
}
DTO de respuesta
// UserDto.cs
namespace MyApp.Application.Features.Users.Queries.GetUserById;
public record UserDto
{
public Guid Id { get; init; }
public string Email { get; init; } = string.Empty;
public string FullName { get; init; } = string.Empty;
public DateTime CreatedAt { get; init; }
public bool IsActive { get; init; }
}
PARTE 4: BEHAVIOURS (Pipeline de Mediator)
⚠️ NOTA IMPORTANTE sobre MediatR vs Mediator
- MediatR v13+ es comercial desde la 13.0.0 (julio de 2025); la 12.4.1 sigue siendo Apache-2.0 (nuget.org)
- Recomendamos usar Mediator (MIT, gratuito)
- Mediator usa source generators → mejor rendimiento, sin reflexión
- La API es casi idéntica, migración sencilla
- Ver
_patron/01_Estructura_Tecnica/GUIA_ARQUITECTURA.mdpara detalles
Behaviour de Validación
// ValidationBehaviour.cs
namespace MyApp.Application.Common.Behaviours;
public class ValidationBehaviour<TRequest, TResponse>
: IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
private readonly IEnumerable<IValidator<TRequest>> _validators;
public ValidationBehaviour(IEnumerable<IValidator<TRequest>> validators)
{
_validators = validators;
}
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
if (!_validators.Any())
return await next();
var context = new ValidationContext<TRequest>(request);
var validationResults = await Task.WhenAll(
_validators.Select(v => v.ValidateAsync(context, cancellationToken)));
var failures = validationResults
.SelectMany(r => r.Errors)
.Where(f => f is not null)
.ToList();
if (failures.Count > 0)
throw new ValidationException(failures);
return await next();
}
}
Behaviour de Logging
// LoggingBehaviour.cs
namespace MyApp.Application.Common.Behaviours;
public class LoggingBehaviour<TRequest, TResponse>
: IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
private readonly ILogger<LoggingBehaviour<TRequest, TResponse>> _logger;
private readonly ICurrentUserService _currentUserService;
public LoggingBehaviour(
ILogger<LoggingBehaviour<TRequest, TResponse>> logger,
ICurrentUserService currentUserService)
{
_logger = logger;
_currentUserService = currentUserService;
}
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
var requestName = typeof(TRequest).Name;
var userId = _currentUserService.UserId;
_logger.LogInformation(
"Ejecutando {RequestName} por User {UserId}: {@Request}",
requestName, userId, request);
var response = await next();
_logger.LogInformation(
"Completado {RequestName} por User {UserId}",
requestName, userId);
return response;
}
}
PARTE 5: INTERFACES DE APPLICATION
IUnitOfWork
// IUnitOfWork.cs
namespace MyApp.Application.Common.Interfaces;
public interface IUnitOfWork
{
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}
ICurrentUserService
// ICurrentUserService.cs
namespace MyApp.Application.Common.Interfaces;
public interface ICurrentUserService
{
string? UserId { get; }
string? UserName { get; }
bool IsAuthenticated { get; }
IEnumerable<string> Roles { get; }
}
IDateTime
// IDateTime.cs
namespace MyApp.Application.Common.Interfaces;
public interface IDateTime
{
DateTime Now { get; }
DateTime UtcNow { get; }
}
PARTE 6: EXCEPCIONES DE APPLICATION
// ValidationException.cs
namespace MyApp.Application.Common.Exceptions;
public class ValidationException : Exception
{
public IDictionary<string, string[]> Errors { get; }
public ValidationException()
: base("Se han producido uno o más errores de validación.")
{
Errors = new Dictionary<string, string[]>();
}
public ValidationException(IEnumerable<ValidationFailure> failures)
: this()
{
Errors = failures
.GroupBy(e => e.PropertyName, e => e.ErrorMessage)
.ToDictionary(g => g.Key, g => g.ToArray());
}
}
// NotFoundException.cs
namespace MyApp.Application.Common.Exceptions;
public class NotFoundException : Exception
{
public NotFoundException()
: base() { }
public NotFoundException(string message)
: base(message) { }
public NotFoundException(string name, object key)
: base($"Entidad \"{name}\" ({key}) no encontrada.") { }
}
// ForbiddenAccessException.cs
namespace MyApp.Application.Common.Exceptions;
public class ForbiddenAccessException : Exception
{
public ForbiddenAccessException()
: base("No tiene permisos para realizar esta acción.") { }
}
PARTE 7: DEPENDENCY INJECTION
Usando Mediator (Recomendado - MIT/Gratuito)
// DependencyInjection.cs
namespace MyApp.Application;
public static class DependencyInjection
{
public static IServiceCollection AddApplication(this IServiceCollection services)
{
var assembly = Assembly.GetExecutingAssembly();
// AutoMapper
services.AddAutoMapper(assembly);
// FluentValidation
services.AddValidatorsFromAssembly(assembly);
// Mediator (martinothamar) - MIT license, source generators
services.AddMediator(options =>
{
options.ServiceLifetime = ServiceLifetime.Scoped;
});
// Pipeline Behaviors (misma sintaxis que MediatR)
services.AddScoped(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>));
services.AddScoped(typeof(IPipelineBehavior<,>), typeof(LoggingBehaviour<,>));
return services;
}
}
Usando MediatR (Solo si ya tienes licencia comercial)
// ⚠️ MediatR v13+ requiere licencia comercial (la 12.x sigue en Apache-2.0)
// Solo usar si la organización ya tiene licencia activa
public static IServiceCollection AddApplication(this IServiceCollection services)
{
services.AddMediatR(cfg => {
cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>));
cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(LoggingBehaviour<,>));
});
return services;
}
REGLAS CRÍTICAS
✅ SIEMPRE
- Usar records para Commands y Queries (inmutabilidad)
- Un archivo por Command/Query/Handler
- Validar inputs con FluentValidation antes del Handler
- Usar
CancellationTokenen todos los métodos async - DTOs específicos por Query (no reutilizar entidades)
❌ NUNCA
- Inyectar DbContext directamente (usar repositorios)
- Lógica de negocio en Handlers (pertenece al Domain)
- Referencias a Infrastructure o Presentation
- Usar Entity Framework directamente
- Exponer entidades de dominio como respuesta
PAQUETES NUGET RECOMENDADOS
<ItemGroup>
<!-- ⚠️ Mediator (MIT/gratuito) en lugar de MediatR (comercial v13+) -->
<PackageReference Include="Mediator.Abstractions" Version="3.*" />
<PackageReference Include="Mediator.SourceGenerator" Version="2.*" OutputItemType="Analyzer" />
<PackageReference Include="FluentValidation" Version="11.*" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.*" />
<!-- ⚠️ Mapperly (Apache-2.0, source generator) en lugar de AutoMapper (comercial v15+) -->
<PackageReference Include="Riok.Mapperly" Version="4.*" PrivateAssets="all" />
<!-- Solo si el proyecto YA usa AutoMapper: rango cerrado para no entrar en la v15 comercial.
El paquete .Extensions.Microsoft.DependencyInjection NO se referencia: la v13 lo absorbio. -->
<!-- <PackageReference Include="AutoMapper" Version="[13.0.0,15.0.0)" /> -->
</ItemGroup>
¿Por qué Mediator en lugar de MediatR?
- MediatR v13+ requiere licencia comercial (la 12.x sigue en Apache-2.0)
- Mediator es MIT (gratuito), usa source generators (mejor rendimiento)
- API compatible, migración sencilla
- Más info:
GUIA_ARQUITECTURA.mdsección "Mediator vs MediatR"
REFERENCIAS
| Capa | Puede usar |
|---|---|
| Application | → Domain (interfaces de repositorios) |
| Application | ✗ Infrastructure |
| Application | ✗ Presentation/API |
Coste de contexto
Descripción de 86 caracteres publicados al modelo en el listado de skills; tope 1536. Cuerpo: 645 palabras, se carga solo al activarse.
Historial
9 cambios · 2026-09-07 → 2026-09-21. Último cambio: feat(puertas): la octava mira donde ninguna miraba (ADR-066) (b849ea6).