FluentValidation:如何注入所有已注册的验证器?
FluentValidation: How to inject all registered validators?
我正在为 .Net Core 项目使用 FluentValidation.AspNetCore 库(Version="10.3.3")。
为了注册验证器,我使用了这个:
services.AddValidatorsFromAssemblyContaining<TestValidator>();
例如,我 class 调用了 Test,我可以像这样为这个 class 注入验证器:
public class Service : IService
{
private readonly IValidator<Test> _testValidator;
public Service(IValidator<Test> testValidator)
{
_testValidator = testValidator;
}
}
但我不知道如何将所有已注册的验证器作为 IEnumerable 实例注入到我的服务构造函数中。那么正确的做法是什么?
FluentValidation
的 AddValidatorsFromAssemblyContaining
注册了所有验证器 implementing IValidator<T>
from assembly as generic interface and self 所以你只能通过具体类型或构造泛型(即 IValidator<Test>
)来解析它们,即这是不可能的将它们全部解析为一个集合。
如果你真的想要,你可以尝试利用 IValidator<T>
继承 IValidator
并使用下一个有点 hacky 的解决方案:
services.AddValidatorsFromAssemblyContaining(typeof(Val1));
// Only after all validators registrations
var serviceDescriptors = services
.Where(descriptor => typeof(IValidator) != descriptor.ServiceType
&& typeof(IValidator).IsAssignableFrom(descriptor.ServiceType)
&& descriptor.ServiceType.IsInterface)
.ToList();
foreach (var descriptor in serviceDescriptors)
{
services.Add(new ServiceDescriptor(
typeof(IValidator),
p => p.GetRequiredService(descriptor.ServiceType),
descriptor.Lifetime));
}
之后您将能够解决 IEnumerable<IValidator>
。虽然不确定这对你有多大帮助。
我正在为 .Net Core 项目使用 FluentValidation.AspNetCore 库(Version="10.3.3")。
为了注册验证器,我使用了这个:
services.AddValidatorsFromAssemblyContaining<TestValidator>();
例如,我 class 调用了 Test,我可以像这样为这个 class 注入验证器:
public class Service : IService
{
private readonly IValidator<Test> _testValidator;
public Service(IValidator<Test> testValidator)
{
_testValidator = testValidator;
}
}
但我不知道如何将所有已注册的验证器作为 IEnumerable 实例注入到我的服务构造函数中。那么正确的做法是什么?
FluentValidation
的 AddValidatorsFromAssemblyContaining
注册了所有验证器 implementing IValidator<T>
from assembly as generic interface and self 所以你只能通过具体类型或构造泛型(即 IValidator<Test>
)来解析它们,即这是不可能的将它们全部解析为一个集合。
如果你真的想要,你可以尝试利用 IValidator<T>
继承 IValidator
并使用下一个有点 hacky 的解决方案:
services.AddValidatorsFromAssemblyContaining(typeof(Val1));
// Only after all validators registrations
var serviceDescriptors = services
.Where(descriptor => typeof(IValidator) != descriptor.ServiceType
&& typeof(IValidator).IsAssignableFrom(descriptor.ServiceType)
&& descriptor.ServiceType.IsInterface)
.ToList();
foreach (var descriptor in serviceDescriptors)
{
services.Add(new ServiceDescriptor(
typeof(IValidator),
p => p.GetRequiredService(descriptor.ServiceType),
descriptor.Lifetime));
}
之后您将能够解决 IEnumerable<IValidator>
。虽然不确定这对你有多大帮助。