我想将数据传递给流畅的验证。我认为这很简单,你可以在构造函数中完成。但我不想创建验证器的实例,而是注入它,这使得它变得很困难。
我有:
public class someClassValidator : AbstractValidator<someClass>
{
public someClassValidator (List<dataModel> data)
{
//do validation
}
}
}
public controller SomeClassController : Controller
{
private readonly someClassValidator _someClassValidator;
public SomeClassController (someClassValidator someClassValidator )
{
_someClassValidator = someClassValidator;
}
public void Update(ClassModel)
{
var moreData = getSomeApiData (List<dataModel> data);
var result = _someClassValidator.Validate(model, moreData);
**// how do I pass data here?**
}
}
我知道你绝对可以 new ValidatorClass(pasaData) 但我不确定它在依赖场景中如何工作
您需要在依赖容器中注册您的验证器。如果您使用的是 asp.net core 的默认 DI,您可以按照 FluentValidation 文档中的建议进行操作。
public class UserValidator : AbstractValidator<User>
{
public UserValidator()
{
RuleFor(x => x.Name).NotNull();
}
}
public class UserService
{
private readonly IValidator<User> _validator;
public UserService(IValidator<User> validator)
{
_validator = validator;
}
public async Task DoSomething(User user)
{
var validationResult = await _validator.ValidateAsync(user);
}
}
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddScoped<IValidator<User>, UserValidator>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
}
}
您需要的是RootContextData。它有一个字典,可以将您的数据放入上下文中并在验证器中获取数据。您的案例可能如下所示:
public void Update(ClassModel classModel)
{
// Creating context by passing the model to validate
var context = new ValidationContext<ClassModel>(classModel);
var moreData = getSomeApiData (List<dataModel> data);
context.RootContextData["MyCustomData"] = moreData;
// Passing context to validatior instead of the model
var result = _someClassValidator.Validate(context);
}
要获取数据,您的验证器可能如下所示:
// The .Custom method gives you access to the context
// You can get your data from the context.RootContextData dictionary
RuleFor(classModel => classModel.Property)
.Custom((property, context) =>
{
if (context.RootContextData.ContainsKey("MyCustomData"))
{
var moreData= (List<dataModel>)context.RootContextData["MyCustomData"];
if (moreData.Failed)
{
context.AddFailure("You shall not pass!!!");
}
}
})
这里是Fluent 验证文档
您可以在此处找到完整的工作示例。搜索 RootContextData