CodexBloom - Programming Q&A Platform

implementing FluentValidation and ASP.NET Core Dependency Injection for Custom Validators

👀 Views: 51 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
asp.net-core fluentvalidation dependency-injection C#

Hey everyone, I'm running into an issue that's driving me crazy. I'm experimenting with I'm performance testing and This might be a silly question, but I'm running into a question with `FluentValidation` in my ASP.NET Core 6 application. I have a custom validator that relies on a service injected via the constructor, but it seems like the validation isn't picking up the dependency correctly, leading to a `ValidationException`. Here's a simplified version of my validator: ```csharp public class UserValidator : AbstractValidator<User> { private readonly IUserService _userService; public UserValidator(IUserService userService) { _userService = userService; RuleFor(x => x.Email) .MustAsync(async (email, cancellation) => await _userService.IsEmailUnique(email)) .WithMessage("Email must be unique."); } } ``` I've registered my `UserValidator` in the `Startup.cs` like this: ```csharp services.AddTransient<IValidator<User>, UserValidator>(); services.AddTransient<IUserService, UserService>(); ``` When I try to validate a `User` object, I get the following behavior: ``` System.InvalidOperationException: Unable to resolve service for type 'MyApp.Services.IUserService' while attempting to activate 'MyApp.Validators.UserValidator'. ``` I've confirmed that `IUserService` is properly registered and I'm not working with any issues with other services relying on it. I tried using `AddScoped` instead of `AddTransient`, but the same behavior occurs. I also tried to create a `ServiceProvider` manually and use it to resolve the validator, but that led to additional complexity without solving the question. What might be causing this scenario with the dependency injection and FluentValidation? Any suggestions on how to ensure that my custom validator can access its dependencies correctly? My development environment is Ubuntu 22.04. What's the best practice here? Could someone point me to the right documentation? The stack includes C# and several other technologies.