7

I have a custom DataAnnotationsModelValidatorProvider for doing model validation in a more dynamic way then just adding attributes. I tried to add my provide to the global.asax.cs like so:

ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new AttributeValidatorProvider());

But once I load my form, I get an error saying "Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: required".

According to a comment on this blog, this is because Ninject is overriding custom validator providers.

I'm fairly new to MVC and I can't seem to find a way to tell Ninject to accept my custom providers as well, how would I go about fixing this problem?

For the record: I do not wish to use Fluentvalidation.net, I want to stick with the default MVC validations (for the most part).

Remo Gloor
  • 32,665
  • 4
  • 68
  • 98
sebastiaan
  • 5,870
  • 5
  • 38
  • 68

2 Answers2

9

There is another way (works in MVC 4 for sure):

Find your class which inherit IdependencyResolver interface and add to constructor _kernel.Unbind<ModelValidatorProvider>(); - you just unbind ninject validator and there should be no colission with default validator.

In my case my constructor looks like this:

public NinjectDependencyResolver()
{
       _kernel = new StandardKernel();
       _kernel.Unbind<ModelValidatorProvider>();
       AddBindings();
}
1_bug
  • 5,505
  • 4
  • 50
  • 58
8

Change the registration of the provider to

Rebind<ModelValidatorProvider>().To<AttributeValidatorProvider>();
Remo Gloor
  • 32,665
  • 4
  • 68
  • 98
  • 1
    I can't seem to get Ninject to work with the built in DataAnnotationsModelValidatorProvider, even with trying the Rebind like you mention. It appears that out of the box, Ninject breaks validation. What is the default for Ninject and how do I use the built in DataAnnotations with Ninject. I've searched a lot and didn't find documentation, blog posts or articles with a working solution. – Greg Levenhagen Feb 20 '12 at 15:03
  • Have a look at the sample application: https://github.com/ninject/ninject.web.mvc/blob/master/mvc3/src/SampleApplication/Models/Movie/PriceRangeAttribute.cs – Remo Gloor Feb 20 '12 at 17:40
  • Thanks! I was missing the load of the executing assembly; only had my services and modules loading. – Greg Levenhagen Feb 29 '12 at 23:45
  • I'm also having this problem but in slightly different circumstances, can you have a look at my answer below? – AdamH Apr 10 '12 at 05:57