2

Is it possible to use C# DataAnnotations with IOC containers? I've got a ValidationAttribute that I'd like to inject a resolved object into the attribute class after the class is instantiated. Basicly, I want to access an annotation from an instantiated class. Or maybe I'm thinking about this backwords and should use validationContext.ObjectInstance?

  • Maybe I miss-understood are you trying to inject a resolved object into a attribute class? As in a dependency for you attribute? – TheCodeKing Sep 12 '11 at 11:08
  • TheCodeKing - Yea, I need to call a method from within the Validation Attribute and I'd like to pass in a provider instead of hard wiring a data connection in my attribute class. –  Sep 12 '11 at 14:04
  • That's what I thought, in which case my answer is the only way I believe this is possible (unless down voter knows another) – TheCodeKing Sep 12 '11 at 15:00
  • A drive by I guess. Thank you –  Sep 14 '11 at 04:33

1 Answers1

0

There's no clean way of using this (with DI). You can however use IoC if you create a static method to access the current IoC Container. It's pretty nasty but it's the only solution I found.

By static I mean static accessor that grabs it from the application or request cache.

TheCodeKing
  • 19,064
  • 3
  • 47
  • 70
  • It's good for mitigation. You can write your application with your favourite IoC patterns, and when you need to use your ResourceProvider instance (which is property injected in everything else) for DataAnnototations you can at least do it somehow without redesigning everything else. – vinczemarton Nov 26 '14 at 13:40