Can't inject service in ValidationAttribute
See original GitHub issueIs there an existing issue for this?
- I have searched the existing issues
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):
public class NamesService
{
public List<string> Names { get; set; } = new() { "Guillermo", "Cinthy" };
public bool IsAValidName(string Name) {
return Names.Contains(Name);
}
}
Then I basically injected this as an Scoped service on my program.cs as follow:
builder.Services.AddScoped<NamesService>();
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:
- Using the IValidatableObject like this, and you can see I made a breakpoint and the value is NULL:
- Ok, so I created a Custom Validation Attribute and the result is the same, like this:
Now I noticed several other options on the context, like:
- validationContext.InitializeServiceProvider
- validationContext.CreateAsyncScope
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
Issue Analytics
- State:
- Created 2 years ago
- Comments:9 (7 by maintainers)
Top GitHub Comments
API review:
Approved with a change to the obsolete warning message:
Closing as the API review comments were addressed.