first commit

This commit is contained in:
2026-02-26 14:04:18 +07:00
parent 57ac80a666
commit 4b7236493f
92 changed files with 4999 additions and 0 deletions

View File

@@ -0,0 +1,49 @@
using System.Diagnostics;
using MediatR;
using Microsoft.Extensions.Logging;
namespace MyNewProjectName.Application.Behaviors;
/// <summary>
/// Logging behavior for MediatR pipeline
/// </summary>
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger;
public LoggingBehavior(ILogger<LoggingBehavior<TRequest, TResponse>> logger)
{
_logger = logger;
}
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
var requestName = typeof(TRequest).Name;
_logger.LogInformation("Handling {RequestName}", requestName);
var stopwatch = Stopwatch.StartNew();
try
{
var response = await next();
stopwatch.Stop();
_logger.LogInformation("Handled {RequestName} in {ElapsedMilliseconds}ms",
requestName, stopwatch.ElapsedMilliseconds);
return response;
}
catch (Exception ex)
{
stopwatch.Stop();
_logger.LogError(ex, "Error handling {RequestName} after {ElapsedMilliseconds}ms",
requestName, stopwatch.ElapsedMilliseconds);
throw;
}
}
}

View File

@@ -0,0 +1,47 @@
using FluentValidation;
using MediatR;
namespace MyNewProjectName.Application.Behaviors;
/// <summary>
/// Validation behavior for MediatR pipeline
/// </summary>
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
private readonly IEnumerable<IValidator<TRequest>> _validators;
public ValidationBehavior(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
.Where(r => r.Errors.Any())
.SelectMany(r => r.Errors)
.ToList();
if (failures.Any())
{
var errors = failures
.GroupBy(e => e.PropertyName, e => e.ErrorMessage)
.ToDictionary(g => g.Key, g => g.ToArray());
throw new MyNewProjectName.Domain.Exceptions.ValidationException(errors);
}
return await next();
}
}