-
Notifications
You must be signed in to change notification settings - Fork 10.7k
Can't inject service in ValidationAttribute #39382
Copy link
Copy link
Closed
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-blazorIncludes: Blazor, Razor ComponentsIncludes: Blazor, Razor ComponentsenhancementThis issue represents an ask for new feature or an enhancement to an existing oneThis issue represents an ask for new feature or an enhancement to an existing onefeature-blazor-form-validationThis issue is related to forms validation in BlazorThis issue is related to forms validation in Blazor
Milestone
Metadata
Metadata
Assignees
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-blazorIncludes: Blazor, Razor ComponentsIncludes: Blazor, Razor ComponentsenhancementThis issue represents an ask for new feature or an enhancement to an existing oneThis issue represents an ask for new feature or an enhancement to an existing onefeature-blazor-form-validationThis issue is related to forms validation in BlazorThis issue is related to forms validation in Blazor
Type
Fields
Give feedbackNo fields configured for issues without a type.
Is there an existing issue for this?
Describe the bug
Dear friends, yes, it's me again to bother you again! :-(
I love learning and found an article that woke up my mind, it was about creating a custom validation attribute (ValidationAttribute) but trying to inject a service (X) in order to get access to data or a method, etc... the idea sounds like a real project and I decided to give it a try... unfortunately every time I try to get a service I just get NULL... and yes, I tried to get some help from the MS help but the documentation is poor, no examples. (except a simple one where you learn how to override the IsValid method)
I created a simple class with a list of names and a method... the idea is that the Validation Attribute inject this as a service and then may ask the method if the name is valid or not... (if is on the list):
Then I basically injected this as an Scoped service on my program.cs as follow:
I did try to inject the service on a regular class and it works, also on a Blazor page and it works also... now, I created another class where I tried in 2 ways:
Now I noticed several other options on the context, like:
But no examples or what's the purpose or how to use these options? or will this help resolve the problem I'm facing?
Thank you for your help, this will help with what's being said all around... https://andrewlock.net/injecting-services-into-validationattributes-in-asp-net-core/
Expected Behavior
No response
Steps To Reproduce
No response
Exceptions (if any)
No response
.NET Version
6
Anything else?
No response