ASP.NET Core API,Mediatr 发送方法引发无法解析类型服务的异常

我有一个 ASP.NET Core API,我正在尝试将 FluentValidation 与 Mediatr 一起使用。

当前,当控制器方法尝试在它生成的 mediatr 实例上调用 Send 时:

抛出的异常:Microsoft.Extensions.DependencyInjection.dll 中的“System.InvalidOperationException”:“尝试激活‘GetApplicationQueryValidator’时无法解析‘GetApplicationQuery’类型的服务。”

查询、验证器和响应类如下所示:

public class GetApplicationQuery : IRequest<Response>

{

    private string _name;

    public GetApplicationQuery(string name)

    {

        _name = name;

    }


    public string Name { get { return _name; } }

}


public class GetApplicationQueryHandler : IRequestHandler<GetApplicationQuery, Response>

{


    public GetApplicationQueryHandler() { }


    public async Task<Response> Handle(GetApplicationQuery request, CancellationToken cancellationToken)

    {

        return new Response("yadda yadda");            

    }

}


public class GetApplicationQueryValidator : AbstractValidator<GetApplicationQuery>

{

    public GetApplicationQueryValidator(GetApplicationQuery request)

    {   

        RuleFor(m => m.Name).MinimumLength(30).WithMessage("Name must be greater than 30 characters, long");

    }

}


public class Response

{

    private readonly IList<string> _messages = new List<string>();


    public IEnumerable<string> Errors { get; }

    public object Result { get; }


    public Response() => Errors = new ReadOnlyCollection<string>(_messages);


    public Response(object result) : this() => Result = result;


    public Response AddError(string message)

    {

        _messages.Add(message);

        return this;

    }

}

我在 Startup 类中的配置如下所示:


public void ConfigureServices(IServiceCollection services)

{

    AddMediatr(services);

    services.AddMvc().AddFluentValidation(fv => 

        {

            fv.RegisterValidatorsFromAssemblyContaining<Startup>();

            fv.RunDefaultMvcValidationAfterFluentValidationExecutes = false;

        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);           

}

蝴蝶不菲
浏览 150回答 1
1回答

偶然的你

GetApplicationQueryValidator正在GetApplicationQuery作为构造函数依赖项,但集合不知道它是否能够注入它。也没有看到它是如何在该验证器中使用的。我建议GetApplicationQuery从构造函数中删除,因为它看起来并不需要。public class GetApplicationQueryValidator : AbstractValidator<GetApplicationQuery> {&nbsp; &nbsp; public GetApplicationQueryValidator() {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; RuleFor(m => m.Name).MinimumLength(30).WithMessage("Name must be greater than 30 characters, long");&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP