我正在使用 FluentValidation 和 Ninject。我正在尝试将服务注入 AbstractValidator
[Validator(typeof(CompetitionFormModelValidator))]
public class CompetitionFormModel
{
public string FirstName { get; set; }
}
为了我的验证:
public class CompetitionFormModelValidator : AbstractValidator<CompetitionFormModel>
{
IUserService UserService;
public CompetitionFormModelValidator(IUserService UserService)
{
this.UserService= UserService;
RuleFor(c => c.FirstName).NotEmpty().WithMessage(" ").Length(1, 100);
Custom(c =>
{
//.. try uusing UserService here
return null;
});
}
}
在我的 global.asax.cs
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
var ninjectValidatorFactory = new NinjectValidatorFactory(new StandardKernel());
ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(ninjectValidatorFactory));
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
FluentValidationModelValidatorProvider.Configure(x => x.ValidatorFactory = ninjectValidatorFactory);
}
在 NinjectWebCommon.cs
private static void RegisterServices(IKernel kernel)
{
AssemblyScanner.FindValidatorsInAssembly(Assembly.GetExecutingAssembly())
.ForEach(match => kernel.Bind(match.InterfaceType)
.To(match.ValidatorType));
kernel.Bind<IUserService>().To<UserService>();
}
该项目编译得很好。当我不尝试使用 DI 时,验证也可以正常工作。现在我正在尝试注入 IUserService,不会调用验证。
我是否正确设置了 ninject.web.mvc.fluentvalidation 的配置?任何帮助将不胜感激。