NOTE: We initially posted this as a question on StackOverflow and Github Discussions.
While we did receive an answer we're still certain that this is a bug either in implementation or in documentation.
When the IsValid method of a ValidationAttribute is called its ValidationContext has the service provider set to null so all calls to GetService return nothing.
I believe this was fixed for MVC: https://github.com/aspnet/Mvc/issues/6346
Every google search eventually ends up at this blog post: https://andrewlock.net/injecting-services-into-validationattributes-in-asp-net-core/
He illustrates that this technique does work there. Now with Blazor this seems to fail.
I believe this should either be documented or fixed, it surprised us and it's not super obvious what the alternatives are.
https://github.com/lfrancke/aspnet-validation-minimal
https://github.com/lfrancke/aspnet-validation-minimal/blob/master/Pages/Index.razor#L18-L20
service is null here.
.NET Core SDK (reflecting any global.json):
Version: 3.1.300
Commit: b2475c1295
Runtime Environment:
OS Name: Mac OS X
OS Version: 10.15
OS Platform: Darwin
RID: osx.10.15-x64
Base Path: /Users/lars/.dotnet/sdk/3.1.300/
Host (useful for support):
Version: 3.1.4
Commit: 0c2e69caa6
.NET Core SDKs installed:
3.1.300 [/Users/lars/.dotnet/sdk]
.NET Core runtimes installed:
Microsoft.AspNetCore.App 3.1.4 [/Users/lars/.dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 3.1.4 [/Users/lars/.dotnet/shared/Microsoft.NETCore.App]
To install additional .NET Core runtimes or SDKs:
https://aka.ms/dotnet-download
@lfrancke thanks for contacting us.
Injecting services for validation is not a feature Blazor offers.
@pranavkm can correct me.
Thanks for the quick reply.
That's fine. In that case it'd be great if that could be documented somewhere (preferably in the ValidationAttribute docs).
My validation library will let you use FluentValidation and dependency injection
I'm wondering: Shouldn't this behavior be documented in the code documentation somehow?
As far as I can tell you closed the issue without any actions.
Injecting services for validation is not a feature Blazor offers.
This is not obvious anywhere right now. Especially not on the ValidationAttribute class itself.
@lfrancke there is already a validation issue that you filed. We don't plan to make any code change for this. Or do you have a specific suggestion?
Sorry, excuse my ignorance.
Which I assume is generated from the documentation in the code itself.
Not sure what the .NET term is (the equivalent to Javadoc in Java) for in code documentation.
@lfrancke we can't add docs there. That lives within the dotnet runtime itself and is applicable to many other contexts that are not Blazor. I'm ok adding a note on the docs about this in the Blazor docs, but I don't think it is a good idea to put it on the class itself since it only applies to Blazor.
Hope that helps.
Understood. Thank you for explaining.