【问题标题】:Fluent Validator .Net Core Injection Dependency Not WorkingFluent Validator .Net Core 注入依赖不起作用
【发布时间】:2020-04-07 19:38:15
【问题描述】:

我正在尝试验证派生类,并且我还想验证基类。这是代码,我在 EmployeeValidator 构造函数上有以下错误:

没有给出与“PersonValidator.PersonValidator”所需的形参“personRepository”相对应的参数

    public class Person
    {
        public string FullName { get; set; }
        public int IDCard  { get; set; }
    }

    public class Employee : Person
    {
        public string Position { get; set; }
        public int EmployeeRecord { get; set; }

    }

    public class PersonValidator<T> : AbstractValidator<T> where T : Person
    {
        public PersonValidator(IPersonRepository personRepository)
        {
            RuleFor(b => b.FullName).NotNull();

            RuleFor(x => x)
            .Must(x => !personRepository.ExistsIDCard(x.IDCard))
            .WithErrorCode("IDCardAlreadyExist");
        }
    }

    public class EmployeeValidator : PersonValidator<Employee>
    {
        public EmployeeValidator(IEmployeeRepository employeeRepository)
        {
            RuleFor(d => d.Position).NotNull();

            RuleFor(x => x)
            .Must(x => !employeeRepository.ExistsEmployeeRecord(x.EmployeeRecord))
            .WithErrorCode("EmployeeRecordAlreadyExist");
        }
    }

使用 FluentValidation 框架验证 EmployeeValidator 而不为基类(Person)的字段复制规则的适当方法是什么?

【问题讨论】:

    标签: validation inheritance dependency-injection .net-core fluentvalidation


    【解决方案1】:

    您可以调用base 构造函数并将IPersonRepository 传递给它

    public class EmployeeValidator : PersonValidator<Employee>
    {
        public EmployeeValidator(IEmployeeRepository employeeRepository, IPersonRepository personRepository) 
            : base(personRepository)
        {
            RuleFor(d => d.Position).NotNull();
    
            RuleFor(x => x)
            .Must(x => !employeeRepository.ExistsEmployeeRecord(x.EmployeeRecord))
            .WithErrorCode("EmployeeRecordAlreadyExist");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 2021-02-02
      • 1970-01-01
      • 2020-12-20
      相关资源
      最近更新 更多