'FluentValidation: AddValidatorsFromAssemblyContaining<T> results in IValidator<T> not registered
I'm trying to use FluentValidation to validate based on object.GetType() rather than knowing the type at compile time by injecting IValidator<T>, but I am getting null values instead of a valid validator.
Organisation + Validator
namespace ConsoleApp44
{
internal class Organisation
{
public string? Name { get; set; }
}
internal class OrganisationValidator: AbstractValidator<Organisation>
{
public OrganisationValidator()
{
RuleFor(x => x.Name).NotEmpty();
}
}
}
Console app that consumes it
var services = new ServiceCollection();
services.AddValidatorsFromAssemblyContaining<OrganisationValidator>();
services.Add(ServiceDescriptor.Scoped(typeof(IValidatorFactory), typeof(ServiceProviderValidatorFactory)));
var sp = services.BuildServiceProvider();
var org = new Organisation();
var validationFactory = sp.GetRequiredService<IValidatorFactory>(); // Not null
var validator = validationFactory.GetValidator(org.GetType()); // Null
validator = validationFactory.GetValidator<Organisation>(); // Null
validator = sp.GetRequiredService<IValidator<Organisation>>(); // Exception, IValidator<Organisation> not registered
Solution 1:[1]
It seems the executing assembly is diff than from the assembly your validator belongs to
Try changing this line
services.AddValidatorsFromAssemblyContaining<OrganisationValidator>();
to
services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());
Please let me know if that resolves your issue
Regards,
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Guru Stron |
