3
votes

I am in doubt about how to use the factory in Ninject and FluentValidatior.

This article helped me a lot, but I do not understand how to use the factory to instantiate my validators:

I also found some other articles like this but with StructureMap!

Follow the steps I performed

  1. Installed Ninject and FluentValidation via nuget
  2. Installed Ninject.Web.Mvc.FluentValidation for factory class
  3. And now?

When installing the Ninject, he created the NinjectMVC3.cs in App_Start folder so I set my dependencies in RegisterServices method:

kernel.Bind<IHumanValidator>().To<ReCaptchaValidate>().InRequestScope();

In Global.asax the Application_Start method:

var ninjectValidatorFactory = new NinjectValidatorFactory(new StandardKernel());
ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(ninjectValidatorFactory));
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
FluentValidationModelValidatorProvider.Configure();

FluentValidator I have:

public class RegisterCoupleValidator : AbstractValidator<RegisterCoupleModel>
{
    public RegisterCoupleValidator()
    {
        RuleFor(p => p.HumanValidator).SetValidator(new HumanValidator());
    }
}

HumanValidator.cs

public class HumanValidator : PropertyValidator
{
    [Inject]
    public IHumanValidator HumanValidate { get; set; }

    public HumanValidator(IHumanValidator hValidator)
        : this()
    {
        HumanValidate = hValidator;
    }

    public HumanValidator()
        : base("Texto digitado está incorreto. Por favor, tente novamente.")
    { }

    protected override bool IsValid(PropertyValidatorContext context)
    {
        return HumanValidate.IsValid();
    }
}

My questions

  1. In RegisterCoupleValidator class with the factory how do I not have instances the validators? Specifically in new HumanValidator()

  2. In HumanValidator class the HumanValidate property always is null, why?


Obs1: I do not want to instantiate these validators of FluentValidator, I want Ninject to resolve the dependencies for me using this factory.

Obs2: I would not have to access the Ninject kernel, since in several posts I read that this would be an anti-partner.

1

1 Answers

1
votes

Have a look at this blog post. The guy is using a NuGet package to setup FluentValidation with Ninject. It is pretty simple and well explained.