I am trying to automate the validation of my view models, I know I can just add a an attribute to specify my validation but there is an option to set up a factory to automate all that, I looked at: this answer and came up with this using simple injector 3.1:
public class CustomValidatorFactory:ValidatorFactoryBase
{
private readonly Container siContainer;
public CustomValidatorFactory(Container siContainer)
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
this.siContainer = siContainer;
this.siContainer.Register(typeof(IValidator<>), assemblies);
}
public override IValidator CreateInstance(Type validatorType)
{
//var instances = siContainer.GetAllInstances(validatorType);
var implementation = ((IServiceProvider)siContainer).GetService(validatorType);
var validatorInstance = implementation != null ? (implementation as IValidator) : null;
return validatorInstance;
}
}
Then the view model can be something like
public class Person {
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
}
public class PersonValidator : AbstractValidator<Person> {
public PersonValidator() {
RuleFor(x => x.Id).NotNull();
RuleFor(x => x.Name).Length(0, 10);
RuleFor(x => x.Email).EmailAddress();
RuleFor(x => x.Age).InclusiveBetween(18, 60);
}
}
However the implementation variable is always null, I've also tried RegisterCollection but still have the same issue, seems like simple injector does not know how to resolve IValidator when the validator inherits from AbstractValidator(This is the class that implements IValidator)