We want to try to increase performance in one microservice of our solution, that's why we have decided to try the FlatValidator in the part of the data validation. I'm new with such approach, at first glance it looks like very simple but I have to get an access to HttpContext into the derived class and it does not work.
public record class RateRequest(Guid RateId, string Metadata);
public class RateRequestValidator : FlatValidator<RateRequest>
{
public RateRequestValidator(HttpContext httpContext)
{
if (httpContext.Request.Method == HttpMethods.Post)
{
ValidIf(m => m.RateId == Guid.Empty,
m => $"Bad HTTP method ({httpContext.Request.Method}).",
m => m.RateId);
}
else if (httpContext.Request.Method == HttpMethods.Put)
{
ValidIf(m => m.RateId != Guid.Empty,
m => $"Bad HTTP method ({httpContext.Request.Method}).",
m => m.RateId);
}
}
}
But it gives me the error: System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: System.Validation.IFlatValidator`1[RateRequest] Lifetime: Transient ImplementationType: RateRequestValidator'...
Please, help me to figure out this problem.
Advice of @'Arthur Edgarov' was correct. Yes, the problem was not related to FlatValidator, the HttpContext can not be reached directly, only via IHttpContextAccessor.