I am using FluentValidation and Ninject. I am trying to inject a service into AbstractValidator
[Validator(typeof(CompetitionFormModelValidator))]
public class CompetitionFormModel
{
public string FirstName { get; set; }
}
and for my validation:
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;
});
}
}
In my 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);
}
In 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>();
}
The project compiles just fine. When I wasn’t trying to use DI, validation was working just fine too. Now that I am trying inject IUserService, validation isn’t called.
Have I set up the configuration of ninject.web.mvc.fluentvalidation properly ? Any help would be greatly appreciated.
In your Application_Start, you new up the
NinjectValidatorFactorywith a newStandardKernelinstead of using your existing kernel – so the validators you registered on your existing kernel won’t be found by theNinjectValidatorFactory.Moving this block of code to a place where you have access to the existing kernel and passing that in should fix the problem.