10

I need to be able to provide the IComponentContext to my ValidatorFactory to resolve FluentValidation Validators. I am a little stuck.

ValidatorFactory

    public class ValidatorFactory : ValidatorFactoryBase
    {
        private readonly IComponentContext context;

        public ValidatorFactory(IComponentContext context)
        {
            this.context = context;
        }

        public override IValidator CreateInstance(Type validatorType)
        {
            return context.Resolve(validatorType) as IValidator;
        }
    }

How do I provide the context and register the ValidatorFactory

FluentValidation.Mvc.FluentValidationModelValidatorProvider.Configure(x => x.ValidatorFactory = new ValidatorFactory());
Sam
  • 15,336
  • 25
  • 85
  • 148

2 Answers2

12

Rather than tightly couple it to Autofac, you can make it generally applicable to any DependencyResolver by using that directly:

public class ModelValidatorFactory : IValidatorFactory
{
  public IValidator GetValidator(Type type)
  {
    if (type == null)
    {
      throw new ArgumentNullException("type");
    }
    return DependencyResolver.Current.GetService(typeof(IValidator<>).MakeGenericType(type)) as IValidator;
  }

  public IValidator<T> GetValidator<T>()
  {
    return DependencyResolver.Current.GetService<IValidator<T>>();
  }
}

Then you can register your validators with any type of DependencyResolver as the strongly-typed IValidator<T> and it will always end up resolving.

Travis Illig
  • 23,195
  • 2
  • 62
  • 85
  • Nice! I like it... I marked yours as the answer instead of mine just for the fact that it is generic now! Thanks – Sam Sep 06 '12 at 16:28
0

I figured this out. If you have the ValidatorFactory take IComponentContext, Autofac injects it automatically.

ValidatorFactory

    public class ValidatorFactory : ValidatorFactoryBase
    {
        private readonly IComponentContext context;

        public ValidatorFactory(IComponentContext context)
        {
            this.context = context;
        }

        public override IValidator CreateInstance(Type validatorType)
        {
            return context.Resolve(validatorType) as IValidator;
        }
    }

Register the ValidatorFactory

FluentValidation.Mvc.FluentValidationModelValidatorProvider.Configure(x => x.ValidatorFactory = new ValidatorFactory());
Sam
  • 15,336
  • 25
  • 85
  • 148