简体   繁体   中英

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. 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. If you create the validator with new or Activator.CreateInstance , there won't be any injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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