FluentValidation Autofac ValidatorFactory

后端 未结 2 2022
囚心锁ツ
囚心锁ツ 2021-02-14 17:20

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

Validato

2条回答
  •  情深已故
    2021-02-14 17:41

    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 GetValidator()
      {
        return DependencyResolver.Current.GetService>();
      }
    }
    

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

提交回复
热议问题