【发布时间】:2021-05-12 01:45:54
【问题描述】:
我是 fluent 新手,正在将其集成到 .NET 核心解决方案中。我试图有一个静态映射器,它根据传递的类型返回适当的验证器,但我遇到了问题。请参阅下面的简单示例:
public static class Mapper
{
public static IValidator GetValidator<T>(T instance)
{
if (instance is CustomType)
{
return new CustomTypeValidator();
}
return new DefaultValidator();
}
public static IValidator<T> GetVlidator<T>(T instance)
{
if (instance is CustomType)
{
return new CustomTypeValidator();
}
return new DefaultValidator();
}
}
第一种方法不可用,因为 IValidator 只提供了一个接受 IValidationContext 的 Validate 方法。
第二种方法无法将具体验证器转换为接口。
我已经研究了 DI 选项,可以为每种类型注册具体验证器,但是我仍然需要根据类型进行映射,并且不能将具体验证器转换为 IValidator
我是否应该只在一个单独的服务上执行验证,在那里我可以根据类型显式执行方法并返回结果?
【问题讨论】:
标签: c# generics .net-core fluentvalidation