问题
I have an asp.net MVC 4.5 application with Castle.Windsor 3.2.2 as DI and I'm trying to add FluentValidation version 5.0.0.1 for the first time.
I created the factory inheriting from ValidatorFactoryBase
public class WindsorFluentValidatorFactory : ValidatorFactoryBase
{
private readonly IKernel _kernel;
public WindsorFluentValidatorFactory(IKernel kernel)
{
_kernel = kernel;
}
public override IValidator CreateInstance(Type validatorType)
{
return _kernel.HasComponent(validatorType)
? _kernel.Resolve<IValidator>(validatorType)
: null;
}
}
Also created the installer for Castle:
public class FluentValidatorsInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Classes
.FromThisAssembly()
.BasedOn(typeof(IValidator<>))
.WithService
.Base());
}
}
Now, in the Global.asax, I tried (following documentation on web) to hook things like this:
var fluentValidationModelValidatorProvider = new FluentValidationModelValidatorProvider(new WindsorFluentValidatorFactory(container.Kernel));
ModelValidatorProviders.Providers.Add(fluentValidationModelValidatorProvider);
However, the second line gives the following error:
"The best overloaded method match for 'System.Collections.ObjectModel.Collection.Add(System.Web.Mvc.ModelValidatorProvider)' has some invalid arguments Argument 1: cannot convert from 'FluentValidation.Mvc.WebApi.FluentValidationModelValidatorProvider' to 'System.Web.Mvc.ModelValidatorProvider'"
So, it seems that this way of doing it is not working on the versions I use.
I also tried to hook this using the Configure method doing this:
FluentValidationModelValidatorProvider.Configure(x => x.ValidatorFactory = new WindsorFluentValidatorFactory(container.Kernel));
However, it's not working. Debugging I checked at ModelValidatorProviders.Providers and there is no new provider being add with the Configure method.
Any ideas on what I might be doing wrong? Thanks,
Andres
Solved I got a solution in another forum but I'll post the answer it's useful for someone else. I was using the wrong Provider There are two providers - one for MVC and one for WebApi. It seems that I was using the WebAPI one.
Changed it to FluentValidation.Mvc.FluentValidationModelValidatorProvide and the problem was solved
来源:https://stackoverflow.com/questions/22256892/issues-setting-up-fluentvalidation-with-castle-windsor