FluentValidation Autofac ValidatorFactory [英] FluentValidation Autofac ValidatorFactory

查看:560
本文介绍了FluentValidation Autofac ValidatorFactory的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够提供 IComponentContext 我的 ValidatorFactory 来解决FluentValidation校验。我有点卡住了。

ValidatorFactory

 公共类ValidatorFactory:ValidatorFactoryBase
    {
        私人只读IComponentContext背景;        公共ValidatorFactory(IComponentContext上下文)
        {
            this.context =背景;
        }        公众覆盖IValidator的CreateInstance(类型validatorType)
        {
            返回context.Resolve(validatorType)为IValidator;
        }
    }

我如何提供上下文和注册 ValidatorFactory

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


解决方案

而不是紧紧它情侣Autofac,您可以使用,使人们普遍适用于任何 DependencyResolver 直接:

 公共类ModelValidatorFactory:IValidatorFactory
{
  公共IValidator GetValidator(类型类型)
  {
    如果(类型== NULL)
    {
      抛出新的ArgumentNullException(类型);
    }
    返回DependencyResolver.Current.GetService(typeof运算(IValidator&所述;&GT)MakeGenericType(类型)。),为IValidator;
  }  公共IValidator< T> GetValidator< T>()
  {
    返回DependencyResolver.Current.GetService< IValidator< T>>();
  }
}

T> 和

然后,你可以与任何类型的 DependencyResolver 作为强类型 IValidator&LT注册您的验证它总是会最终解决。

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());

解决方案

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.

这篇关于FluentValidation Autofac ValidatorFactory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆