FluentValidation:如何从另一个程序集中自动注册所有验证器? [英] FluentValidation: How to register all validators automatically from another assembly?

查看:48
本文介绍了FluentValidation:如何从另一个程序集中自动注册所有验证器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用FluentValidation.AspNetCore".Net Core 项目的库(版本 =8.6.2").

I'm using "FluentValidation.AspNetCore" library (Version="8.6.2") for a .Net Core project.

我想要做的是在 Startup.cs 类中自动注册我所有的验证器,使用这样的东西(这就是我现在正在使用的):

What I would like to do is to register all my Validators automatically in Startup.cs class, using something like this (which is what I'm using now):

services.AddControllers().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());

但问题是我的验证器将被移动到另一个程序集(客户端需要),所以我不能使用 Startup 作为注册的参考.

But the problem is that my validators are going to be moved to another assembly (required by client), so I can't use Startup as reference for the registration.

有没有一种方法可以做到这一点,而不必一个一个地注册验证器?

Is there a way I can do this without having to register the validators one by one?

推荐答案

注册Validator有3种方式.

For registering Validator, there are three ways.

  1. 使用 AddTransient 在 Service 中注册每个验证器.
  2. 使用RegisterValidatorsFromAssemblyContaining"方法注册所有从程序集中的 AbstractValidator 类派生的验证器包含指定的类型.
  3. 使用RegisterValidatorsFromAssembly"方法注册.

来源这里

如果您使用选项编号 2 并将代码中的 Startup 替换为从另一个程序集的 AbstractValidator 派生的任何类,它将注册 all来自该程序集的验证器

If you use option number 2 and replace Startup in your code with any class derived from AbstractValidator from another assembly, it will register all validators from that assembly

示例:

services.AddControllers().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<AnotherValidationClass>());

这篇关于FluentValidation:如何从另一个程序集中自动注册所有验证器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆