Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation Autofac ValidatorFactory

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());
like image 694
Sam Avatar asked Sep 01 '12 05:09

Sam


People also ask

What is FluentValidation C#?

FluentValidation is a .NET library for building strongly-typed validation rules. It Uses a fluent interface and lambda expressions for building validation rules. It helps clean up your domain code and make it more cohesive, as well as giving you a single place to look for validation logic.

What is FluentValidation .NET core?

FluentValidation is a . NET library for building strongly-typed validation rules. FluentValidation 11 supports the following platforms: . NET Core 3.1.

Is fluent validation open source?

Fluent Validation is a popular open source library for solving complex validation requirements written by Jeremy Skinner. You can find the source code and documentation for the library at https://github.com/JeremySkinner/fluentvalidation.

Why is fluent validation?

Advantages of using Fluent ValidationsSpeed of development- It is easy to work with. Decoupling validation rules and models- Fluent Validation allows you to separate validation rules from your model and helps you structure the rules so that they are nice and readable.


1 Answers

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.

like image 193
Travis Illig Avatar answered Sep 25 '22 16:09

Travis Illig