简体   繁体   English

我可以在自定义验证属性的定义中使用依赖项注入吗?

[英]Can I use dependency injection in the definition of a custom validation attribute?

I'm using Prism and Unity for the application, and I have a custom validation attribute that I want to validate the field against a table in the database. 我正在为应用程序使用Prism和Unity,并且我有一个自定义验证属性,我想针对数据库中的表来验证字段。 I would like to inject the Repository service into the validator, but I haven't figured out how to do it. 我想将存储库服务注入到验证器中,但是我还没有弄清楚该如何做。

I have used the dependency attribute on a property, but that didn't work. 我在属性上使用了依赖项属性,但这没有用。 The property remained null. 该属性保持为空。

I tried constructor injection, but it conflicts with the attribute signature. 我尝试了构造函数注入,但是它与属性签名冲突。

Is this possible? 这可能吗? If not, what is another way to accomplish what I'm trying to do? 如果没有,完成我想做的事情的另一种方法是什么?

You get stuff injected into classes that you have the container create for you. 您会将东西注入到为容器创建的类中。

That means, if you create your validator through Resolve or (preferred) have it injected into the class that uses it, constructor injection in the validator itself will work fine. 这意味着,如果您通过Resolve创建验证器或(最好)将其注入使用该验证器的类中,则在验证器本身中进行构造函数注入将可以正常工作。 If you create the validator with new or Activator.CreateInstance , there won't be any injection. 如果使用newActivator.CreateInstance创建验证器,则不会进行任何注入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM