Dependency-Injected Validation in Web API

后端 未结 6 937
遥遥无期
遥遥无期 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:44

    I've finally got this to work, but it's a bit of a bodge. As mentioned earlier, the ModelValidatorProvider will keep Singleton instances of all Validators around, so this was completely unsuitable. Instead, I'm using a Filter to run my own validation, as suggested by Oppositional. This filter has access to the IDependencyScope and can instantiate validators neatly.

    Within the Filter, I go through the ActionArguments, and pass them through validation. The validation code was copied out of the Web API runtime source for DefaultBodyModelValidator, modified to look for the Validator within the DependencyScope.

    Finally, to make this work with the ValidationActionFilter, you need to ensure that your filters are executed in a specific order.

    I've packaged my solution up on github, with a version available on nuget.

提交回复
热议问题