将依赖项注入到验证属性Web Api Asp.Net Core中 [英] Inject Dependencies into Validation Attribute Web Api Asp.Net Core

查看:52
本文介绍了将依赖项注入到验证属性Web Api Asp.Net Core中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Asp.Net Core Web Api中构建自定义验证属性.我需要访问验证器中的IDataProtector和用于访问数据库的其他服务.我已经搜索过,并且没有找到有关此内容的任何文档. ActionFilters可以选择使用ServiceFilter,但似乎没有任何用于Validation Attribute的选项.有什么想法吗?

I'm building a Custom Validation Attribute in Asp.Net Core Web Api. I need to access IDataProtector in my validator and another service I'm using to access the database. I've searched and wasn't ab;e to find any documentation for this. ActionFilters have the option of using ServiceFilter but there doesn't seem to be any option for Validation Attribute. Any ideas?

推荐答案

由于验证属性通常是在属性上定义的,因此它们无法通过构造函数接收引用.充其量,如果您确实真正地进行了模型绑定,则可能需要进行一些自定义以允许属性注入,但是最实际的是,我只是在Validate方法中获得了对依赖关系解析器的引用,并调用了适当的方法.

Because validation attributes are typically defined on properties, they can't receive a reference via the constructor. At best if you did really deep into model binding, there may be something to customize to allow property injection, but most practically I just get a reference to the dependency resolver in the Validate method, and call the appropriate method.

这篇关于将依赖项注入到验证属性Web Api Asp.Net Core中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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