Skip to content

Enhance Validation Behavior Pipeline #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions src/N8T.Infrastructure/Validator/RequestValidationBehavior.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
Expand All @@ -14,13 +16,13 @@ public class RequestValidationBehavior<TRequest, TResponse> : IPipelineBehavior<
where TRequest : notnull, IRequest<TResponse>
where TResponse : notnull
{
private readonly IValidator<TRequest> _validator;
private readonly IEnumerable<IValidator<TRequest>> _validators;
private readonly ILogger<RequestValidationBehavior<TRequest, TResponse>> _logger;

public RequestValidationBehavior(IValidator<TRequest> validator,
public RequestValidationBehavior(IEnumerable<IValidator<TRequest>>? validators,
ILogger<RequestValidationBehavior<TRequest, TResponse>> logger)
{
_validator = validator ?? throw new ArgumentNullException(nameof(validator));
_validators = validators ?? throw new ArgumentNullException(nameof(validators));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

Expand All @@ -34,12 +36,16 @@ public async Task<TResponse> Handle(TRequest request,

_logger.LogDebug($"Handling {typeof(TRequest).FullName} with content {JsonSerializer.Serialize(request)}");

await _validator.HandleValidation(request);

var response = await next();
if (_validators.Any())
{
var context = new ValidationContext<TRequest>(request);
await Task.WhenAll(_validators.Select(v => v.HandleValidation(request)));
}
TResponse? response = await next();

_logger.LogInformation($"Handled {typeof(TRequest).FullName}");
return response;

}
}
}