How to use FluentValidation in the pattern repository when you need to check the uniqueness, for example, login (checked in the database)?
Explanation:
The solution consists of 4 projects:
The structure of the project RTLservise.Model:
UserValidator class:
public class UserValidator : AbstractValidator<User> { public UserValidator() { RuleFor(x => x.Login) .Must(CheckUserName) .WithMessage("Login некорректный."); .Must(IsLoginUnique) .WithMessage("Пользователь с таким логином уже зарегистрирован."); } private bool CheckUserName(string login) { if (login == null) return false; string pattern = @"^[a-zA-Z][a-zA-Z0-9-_\.]{1,49}$"; Regex regex = new Regex(pattern); return regex.IsMatch(login); } } CheckUserName was easy.
BUT: Check the user for uniqueness (execute the function uf_Bit_exists_login ), for example:
public bool IsLoginUnique(string login) { if (login == null) { return false; } using (var connection = new SqlConnection(_connectionString)) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandType = CommandType.StoredProcedure; command.CommandText = "uf_Bit_exists_login"; var returnValue = command.Parameters.AddWithValue("@login", login); returnValue.Direction = ParameterDirection.ReturnValue; command.ExecuteNonQuery(); return (bool)returnValue.Value; } } } And here all the tests immediately fall.
Is it correct to place the check related to connecting to the database exactly in the class of the validator ??
Of course I wanted something, like:
IUserRepository _repository = new UserRepository(); And then check:
_repository.IsLoginUnique(string) BUT: this is impossible, because There are cyclical references :( Then can transfer the validation logic to the service? It is not clear with this design approach, where is the general check?

