let*_*tie 9 c# registration startup fluentvalidation .net-core
我正在为 .Net Core 项目使用“FluentValidation.AspNetCore”库(版本=“8.6.2”)。
我想做的是使用类似这样的东西(这就是我现在使用的)在 Startup.cs 类中自动注册所有验证器:
services.AddControllers().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
Run Code Online (Sandbox Code Playgroud)
但问题是我的验证器将被移动到另一个程序集(客户端需要),所以我不能使用 Startup 作为注册的参考。
有没有一种方法可以做到这一点,而不必一一注册验证器?
Oka*_*dag 14
AddFluentValidation() 已弃用。
来源: https: //github.com/FluentValidation/FluentValidation/issues/1965
老的:
builder.Services.AddControllersWithViews().AddFluentValidation(fv => { });//or AddMvc(), AddMvcCore()
//or
builder.Services.AddFluentValidation(config =>
{
config.ConfigureClientsideValidation(enabled: false);
});
Run Code Online (Sandbox Code Playgroud)
新的 :
builder.Services.AddValidatorsFromAssemblyContaining<AnyValidator>() // register validators
builder.Services.AddFluentValidationAutoValidation(); // the same old MVC pipeline behavior
builder.Services.AddFluentValidationClientsideAdapters(); // for client side
Run Code Online (Sandbox Code Playgroud)
您可以使用官方 nuget 包:
services.AddValidatorsFromAssemblyContaining<SomeValidator>();
或者
services.AddValidatorsFromAssemblyContaining(typeof(SomeValidator));
或者
services.AddValidatorsFromAssembly(typeof(SomeValidator).Assembly);
此处描述了所有可能的 DI 选项
\n\n注册Validator有3种方式。
\n\n
\n- 使用 AddTransient 注册 Service 中的每个验证器。
\n- 使用 \xe2\x80\x9cRegisterValidatorsFromAssemblyContaining\xe2\x80\x9d 方法注册会注册包含指定类型的程序集中从 AbstractValidator 类派生的所有\n验证器。
\n- 使用 \xe2\x80\x9cRegisterValidatorsFromAssembly\xe2\x80\x9d 方法注册。
\n
来源在这里
\n如果您使用选项 2 并Startup在代码中替换为AbstractValidator从另一个程序集派生的任何类,它将注册该程序集中的所有验证器
例子:
\nservices.AddControllers().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<AnotherValidationClass>());\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
33058 次 |
| 最近记录: |