FluentValidation Autofac ValidatorFactory

后端 未结 2 2018
囚心锁ツ
囚心锁ツ 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:36

    I figured this out. If you have the ValidatorFactory take IComponentContext, Autofac injects it automatically.

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

    Register the ValidatorFactory

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

提交回复
热议问题