如何通用地注册所有验证器
How to register all validators generically
我在使用开放泛型类型进行依赖注入时遇到问题。
现在要注册验证器,我必须写:
container.RegisterType<IValidator<User>, UserValidator>();
我需要这样的东西:
container.RegisterType(typeof(IValidator<>), typeof(Validator<>));
其中 UserValidator
class 是
public class UserValidator : Validator<User>
{
public UserValidator()
{
RuleFor(user => user.Email).EmailAddress();
}
}
Unity 容器 支持开放泛型的注册(here 是有人这样做的一个例子),但您想要映射到具体的非泛型classes。内置功能会将开放式通用接口解析为封闭式通用 class.
您尝试注册
container.RegisterType(typeof(IValidator<>), typeof(Validator<>));
将解析为 Validator<User>
,这显然不是您想要的。无法使用内置功能告诉它 "I really want you to resolve to the non-generic subclass of Validator<User>
".
我建议您在 IUnityContainer
上创建一个扩展方法,该方法将反映程序集寻找非通用验证器,并单独注册它们。
我在使用开放泛型类型进行依赖注入时遇到问题。
现在要注册验证器,我必须写:
container.RegisterType<IValidator<User>, UserValidator>();
我需要这样的东西:
container.RegisterType(typeof(IValidator<>), typeof(Validator<>));
其中 UserValidator
class 是
public class UserValidator : Validator<User>
{
public UserValidator()
{
RuleFor(user => user.Email).EmailAddress();
}
}
Unity 容器 支持开放泛型的注册(here 是有人这样做的一个例子),但您想要映射到具体的非泛型classes。内置功能会将开放式通用接口解析为封闭式通用 class.
您尝试注册
container.RegisterType(typeof(IValidator<>), typeof(Validator<>));
将解析为 Validator<User>
,这显然不是您想要的。无法使用内置功能告诉它 "I really want you to resolve to the non-generic subclass of Validator<User>
".
我建议您在 IUnityContainer
上创建一个扩展方法,该方法将反映程序集寻找非通用验证器,并单独注册它们。