0

I have my own ValidatorFactory with structuremap implementation in asp net mvc 3 application.

public class StructureMapValidatorFactory : ValidatorFactoryBase
{
    public override IValidator CreateInstance(Type validatorType)
    {
        return ObjectFactory.TryGetInstance(validatorType) as IValidator;
    }
}

And in global asax ...

FluentValidationModelValidatorProvider.Configure(provider => 
{ 
  provider.ValidatorFactory = new StructureMapValidatorFactory(); 
});

Well, with this combination client validation doesnt work, if i use standard provider configuration, client validation works fine.

Is here any workaround?

Mennion
  • 2,873
  • 3
  • 20
  • 34

2 Answers2

1

Make sure that you have properly configured your DI framework to resolve the validators. If ObjectFactory.TryGetInstance(validatorType) returns null, it won't work because there won't be any validator associated to the model and no metadata will be emitted.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Well, yes in my bootstrap i have explicit registration each fluent validator in structure map, but client validation still not work. – Mennion Aug 20 '12 at 08:44
  • Did you debug your code inside the Configure method? Did you ensure that `ObjectFactory.TryGetInstance(validatorType)` doesn't return null? I guess you haven't because IMHO that's the reason your code doesn't work => there's no validator being returned for the given type. Instead of using StructureMap, try at first hardcoding the corresponding validator: `provider.ValidatorFactory = new MyViewModelValidator();`. – Darin Dimitrov Aug 20 '12 at 08:45
  • Hmm, you are right, var instance = ObjectFactory.TryGetInstance(validatorType) as IValidator returns null – Mennion Aug 20 '12 at 08:57
  • Btw If i set validator manually ([Validator(typeof(validation_class))]) client validation works fine. But I want use DI in my validator class, so how properly configuration my structure map container? – Mennion Aug 20 '12 at 09:10
  • You shouldn't be using `[Validator(typeof(validation_class))]` with a custom `ValidatorFactory`. As far as configuring StructureMap is concerned that's another topic => you could start a new question. – Darin Dimitrov Aug 20 '12 at 09:31
0

Finally, forgot calling Configure method in my boostrap. So,

ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(new StructureMapValidatorFactory()));

and then

FluentValidationModelValidatorProvider.Configure();
Mennion
  • 2,873
  • 3
  • 20
  • 34