What do you think about this idea: Some DTOs need validations that involves database interactions, so we inject DbContext or repository class inside the validator class and use it for validation.
public class UserEditSelfResourceValidator : AbstractValidator<UserEditSelfResource>
{
private IUserRepository _userRepository;
public UserEditSelfResourceValidator(IUserRepository userRepository, ILoggedInUserService loggedInUser)
{
_userRepository = userRepository;
RuleFor(mem => mem.ProfileUrl).MustAsync(async (entity, value, c) => await UniqueProfileUrl(entity, value))
.WithMessage("Profile Url must be unique.");
}
public async Task<bool> UniqueProfileUrl(UserEditSelfResource userEditSelf, string newProfileUrl)
{
var user = await _userRepository.FindByProfileUrlAsync(newProfileUrl);
if(user.Id == _loggedInUser.GetId() || user == null)
{
return true;
}
return false;
}
}
Do you consider such a think as a good practice or something is wrong about that?