FluentValidation Autofac ValidatorFactory

时间:2012-09-01 05:23:31

标签: asp.net-mvc autofac fluentvalidation

我需要能够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());

2 个答案:

答案 0 :(得分:9)

不是将其与Autofac紧密结合,而是通过直接使用它来使其通常适用于任何DependencyResolver

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>,并且它将始终最终解析。

答案 1 :(得分:0)

我想出来了。如果您拥有ValidatorFactory IComponentContext,则Autofac会自动注入。

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