I have a generic class I have created:
public class GenericCreate<T> : IRequest<Attempt<T>> where T: class
{
public T Model { get; }
public GenericCreate(T model) => Model = model;
}
public class GenericCreateHandler<T> : IRequestHandler<GenericCreate<T>, Attempt<T>> where T : class
{
private readonly NotNullValidator<T> _validator;
private readonly DatabaseContext _databaseContext;
public GenericCreateHandler(NotNullValidator<T> validator, DatabaseContext databaseContext)
{
_validator = validator;
_databaseContext = databaseContext;
}
public async Task<Attempt<T>> Handle(GenericCreate<T> request, CancellationToken cancellationToken)
{
var generic = request.Model;
var validationAttempt = _validator.Validate(generic).ToAttempt();
if (validationAttempt.Failure) return validationAttempt.Error;
_databaseContext.Add(generic);
await _databaseContext.SaveChangesAsync(cancellationToken);
return generic;
}
}
As far as the function of the class is concerned, it works. But, I am trying to inject a different validator based on the type of T
.
You can see I am trying to inject NotNullValidator<T>
which is a class in itself:
public class NotNullValidator<T> : AbstractValidator<T>
{
protected override bool PreValidate(ValidationContext<T> context, ValidationResult result)
{
if (context.InstanceToValidate != null) return true;
result.Errors.Add(new ValidationFailure("", "Please ensure a model was supplied."));
return false;
}
}
But what I would like to inject is this:
public class CategoryValidator: NotNullValidator<Category>
{
public CategoryValidator()
{
RuleFor(m => m.Id).NotEmpty();
RuleFor(m => m.Name).NotEmpty();
}
}
As you can imagine, I have a validator class for every entity in the project, so being able to get the correct validator is important. Does anyone know how I can do this using .net core?