Dependency-Injected Validation in Web API

后端 未结 6 938
遥遥无期
遥遥无期 2021-02-04 09:05

In MVC, I can create a Model Validator which can take Dependencies. I normally use FluentValidation for this. This allows me to, for example, check on account registration tha

6条回答
  •  太阳男子
    2021-02-04 09:37

    I spent a lot of time trying to find a good way around the fact that WebApi ModelValidatorProvider stores the validators as singletons. I didn't want to have to tag things with validation filters, so I ended up injecting IKernel in the validator and using that to get the context.

    public class RequestValidator : AbstractValidator{
        public readonly IDbContext context;
    
        public RequestValidator(IKernel kernel) {
            this.context = kernel.Get();
    
            RuleFor(r => r.Data).SetValidator(new DataMustHaveValidPartner(kernel)).When(r => r.RequestableKey == "join");
        }
    }
    

    This seems to work even though the validator is stored as a singleton. If you also want to be able to call it with the context, you could just create a second constructor that takes IDbContext and make the IKernel constructor pass IDbContext using kernel.Get()

提交回复
热议问题