我有一个ASP.NET Core API,我尝试在其中将FluentValidation与Mediatr一起使用。
当前,当控制器方法尝试在其生成的mediatr实例上调用Send时:
抛出异常:“ System.InvalidOperationException” Microsoft.Extensions.DependencyInjection.dll:'无法解析 尝试激活类型为“ GetApplicationQuery”的服务 “ GetApplicationQueryValidator”。
查询,验证器和响应类如下:
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);
}
private static void AddMediatr(IServiceCollection services)
{
const string applicationAssemblyName = "ApplicationApi";
var assembly = AppDomain.CurrentDomain.Load(applicationAssemblyName);
AssemblyScanner
.FindValidatorsInAssembly(assembly)
.ForEach(result => services.AddScoped(result.InterfaceType, result.ValidatorType));
services.AddScoped(typeof(IPipelineBehavior<,>), typeof(ValidatorHandler<,>));
services.AddMediatR(assembly);
}
我猜我的配置错误,但是我几次更改配置都没有成功。
任何指导将不胜感激
答案 0 :(得分:1)
GetApplicationQueryValidator
将GetApplicationQuery
作为构造函数依赖项,但是集合不知道它是否能够注入它。
也没有看到在验证器中如何使用它。我建议从构造函数中删除GetApplicationQuery
,因为它看起来不是必需的。
public class GetApplicationQueryValidator : AbstractValidator<GetApplicationQuery> {
public GetApplicationQueryValidator() {
RuleFor(m => m.Name).MinimumLength(30).WithMessage("Name must be greater than 30 characters, long");
}
}