Home Validation in Business Layer: How to call service methods?
Reply: 0

Validation in Business Layer: How to call service methods?

user2235
1#
user2235 Published in July 16, 2018, 6:37 am

I have created a struct on validating models on Business Layer which is based on Steven's answer.

It is working well but something confuses my mind. I inject UserService in CreateUserValidator to able to use GetUser method. This means I call validator in UserService and create a new UserService instance to check whether user exist.

UserService -> [ValidateUser -> new UserService().GetUser()]

It works but seems to be a very bad design. But I have to use that method.

Could you please let me know how I can solve this problem, or Shouldn't I worry about it?

public class CreateUser
{
    public string Name { get; set; }
    public string Email { get; set; }
}

public sealed class CreateUserValidator : Validator<CreateUser>
{
    private IUserService _userService;
    public CreateUserValidator(IUserService userService)
    {
        _userService = userService;
    }
    protected override IEnumerable<ValidationResult> Validate(
        CreateUser entity)
    {

        var user = _userService.GetUserByEmail(entity.Email);
        if (user != null)
        {
            yield return new ValidationResult("Email", "Email address is already exist!");
        }
    }
}

UserService.cs

public partial class UserService : IUserService
{
    IGenericUnitofWork _uow = null;
    private readonly IValidationProvider _validationProvider;
    public UserService(IGenericUnitofWork uow, IValidationProvider validationProvider)
    {
        _uow = uow;
        _validationProvider = validationProvider;
    }

    public User CreateUser(CreateUser createUser)
    {
        this._validationProvider.Validate(createUser);

        var user = new User()
        {
            Email = createUser.Email,
            Name = createUser.Name,
        };
        _uow.Repository<User>().Insert(User);
        _uow.SaveChanges();
        return user;
    }

    public User GetUser(string email)
    {
        var user = _uow.Repository<User>().Where(m => m.Email == email).FirstOrDefault();
        return user;
    }
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.33375 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO