c# - .NET Core - FluentValidation 注入(inject)

标签 c# asp.net-core-2.1 mediatr

我正在创建 ASP.NET CORE (2.1) 项目并尝试使用 FluentValidation 库 ( https://fluentvalidation.net/ )。不幸的是,当我向我的 ApiController 发送请求时出现错误。

处理请求时发生未处理的异常。

InvalidOperationException: Unable to resolve service for type 'Core.Entities.Estimate' while attempting to activate 'Spinner.Features.Estimates.OnPost+CommandValidator'. Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, bool throwIfCallSiteNotFound)

这是我要验证模型和验证器的类:

public class Command : IRequest<AcceptCostEstimateResponse>
{
    public EstimateDTO Estimate { get; set; }

    public ClientHeaderDTO ClientHeader { get; set; }
}

public class CommandValidator : AbstractValidator<Command>
{
    public CommandValidator(Estimate configuration)
    {
        RuleFor(x => x.Estimate).NotNull();

        RuleFor(x => x.Estimate.Name).NotEmpty();

        RuleFor(x => x.Estimate.Variant).NotEmpty();

        RuleFor(x => x.ClientHeader.ClientName).NotEmpty();

        RuleFor(x => x.ClientHeader.RequestId).NotEmpty();
    }
}

这是我的 Startup.cs - 我存在依赖注入(inject)配置的地方:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());

    services.AddAutoMapper();

    services.AddMediatR();

    services.AddDbContextPool<SpinnerContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    ConfigureCore(services);

    ConfigureRepositories(services);
}

我也尝试过以不同的方式配置 CommandValidator,就像这样,但这仍然没有帮助:

services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        .AddFluentValidation();

services.AddTransient<IValidator<Command>, CommandValidator>();

最佳答案

I removed Estimate configuration parameter inside CommandValidator constructor and now getting different error. An unhandled exception occurred while processing the request. NullReferenceException: Object reference not set to an instance of an object.

对于这个错误,是当EstimateClientHeader 没有值时导致的,它们将为null,FluentValidation 将尝试访问他们的属性。

尝试以下选项:

  • 更改 Command 以设置子属性。

    public class Command : IRequest<AcceptCostEstimateResponse>
    {
        public Command()
       {
           Estimate = new EstimateDTO();
           ClientHeader = new ClientHeaderDTO();
        }
        public EstimateDTO Estimate { get; set; }
        public ClientHeaderDTO ClientHeader { get; set; }
    }
    
  • 更改 CommandValidator 以仅在其不为空时验证子属性。

        public CommandValidator()
    {
        //RuleFor(x => x.Estimate).NotNull();
    
        //RuleFor(x => x.Estimate.Name).NotEmpty();
    
        //RuleFor(x => x.Estimate.Variant).NotEmpty();
    
        //RuleFor(x => x.ClientHeader.ClientName).NotEmpty();
    
        //RuleFor(x => x.ClientHeader.RequestId).NotEmpty();
        RuleFor(x => x).NotNull();
    
        When(x => x != null, () =>
        {
            RuleFor(x => x.Estimate).NotNull();
    
            When(x => x.Estimate != null, () =>
            {
                RuleFor(x => x.Estimate.Name).NotEmpty();
    
                RuleFor(x => x.Estimate.Variant).NotEmpty();
            });
    
            RuleFor(x => x.ClientHeader).NotNull();
    
            When(x => x.ClientHeader != null, () =>
            {
                RuleFor(x => x.ClientHeader.ClientName).NotEmpty();
    
                RuleFor(x => x.ClientHeader.RequestId).NotEmpty();
            });
    
        });
    
    
    }
    

关于c# - .NET Core - FluentValidation 注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51986721/

相关文章:

c# - mysql 存储过程参数似乎不适用于 "@"(At 符号)

Visual Studio 中的 C# 脚本突然中途停止而没有错误

c# - Azure 服务总线队列 - 如何防止 IHostedService 立即处理队列消息

javascript - 在 Jquery 中填充数组并传递给 Controller

c# - 在现有框架中调整/包装 MediatR 通知

asp.net-core - Google Cloud Platform 上的 NET Core 2.1 无法验证 HTTPS 连接 TLS 握手失败,数据包格式意外

c# - 如何在 C# 中解析 OData $filter

c# - Azure Function,返回状态码+JSON,无需在每个逻辑部分定义返回

c# - 如何避免 MediatR 请求处理程序中的代码重复?