Skip to content

Can't inject service in ValidationAttribute #39382

@sipi41

Description

@sipi41

Is 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:

  1. Using the IValidatableObject like this, and you can see I made a breakpoint and the value is NULL:

image

  1. Ok, so I created a Custom Validation Attribute and the result is the same, like this:

image

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

Metadata

Metadata

Assignees

Labels

api-approvedAPI was approved in API review, it can be implementedarea-blazorIncludes: Blazor, Razor ComponentsenhancementThis issue represents an ask for new feature or an enhancement to an existing onefeature-blazor-form-validationThis issue is related to forms validation in Blazor

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions