我最近发现了FluentValidator,并开始尝试依赖注入(inject)。我似乎无法弄清楚如何使用当前的DI设置将值传递给子验证器。

我想从InvoiceDetailsValidator访问Invoice.InvoiceNumber。

public class InvoiceValidator : AbstractValidator<Invoice>
{
    private readonly IDbContextFactory<DbContext> dbContextFactory;

    public InvoiceValidator(InvoiceDetailsValidator invoiceDetailsValidator, IDbContextFactory<DbContext> dbContextFactory)
    {
        ...

        RuleFor(x => x.InvoiceNumber)
            .Must(BeSomething)
            .WithMessage("Invoice number is required.");

        RuleForEach(x => x.InvoiceDetails)
            .SetValidator(invoiceDetailsValidator);
    }
}
public class InvoiceDetailsValidator : AbstractValidator<InvoiceDetails>
{
    public InvoiceDetailsValidator(IDbContextFactory<DbContext> dbContextFactory)
    {
        ...

        RuleFor(x => x.InvoiceSection)
            .NotEmpty()
            .When(X => !string.IsNullOrEmpty( /* InvoiceNumber? */ ))
            .WithMessage("Invoice section is required.");
    }
}

任何帮助将不胜感激。

最佳答案

从更改Paarent验证器构造函数

    public InvoiceValidator(InvoiceDetailsValidator invoiceDetailsValidator,
                            IDbContextFactory<DbContext> dbContextFactory
                           )


    public InvoiceValidator(IValidator<InvoiceDetails> invoiceDetailsValidator,
                            IDbContextFactory<DbContext> dbContextFactory
                           )

关于c# - FluentValidation DI将值传递给 child 验证器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57916636/

10-12 23:01