asp.net-mvc – FluentValidation Autofac ValidatorFactory

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – FluentValidation Autofac ValidatorFactory前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要能够将IComponentContext提供给我的ValidatorFactory来解析FluentValidation Validators.我有点卡住了.

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;
        }
    }

如何提供上下文并注册ValidatorFactory

FluentValidation.Mvc.FluentValidationModelValidatorProvider.Configure(x => x.ValidatorFactory = new ValidatorFactory());

解决方法

您可以通过直接使用它来使其通常适用于任何DependencyResolver,而不是将其与Autofac紧密结合:
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>>();
  }
}

然后,您可以将任何类型的DependencyResolver注册为验证器,作为强类型IValidator< T>它总会最终解决.

原文链接:https://www.f2er.com/aspnet/245205.html

猜你在找的asp.Net相关文章