question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Can't inject service in ValidationAttribute

See original GitHub issue

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

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:9 (7 by maintainers)

github_iconTop GitHub Comments

1reaction
pranavkmcommented, Jan 24, 2022

API review:

Approved with a change to the obsolete warning message:

- [Obsolete("This API is obsolete and will be removed in a future version")]
+ [Obsolete("This API is obsolete and will be removed in a future version. Consider using the overload that accepts an IServiceProvider.")]
0reactions
pranavkmcommented, Jan 27, 2022

Closing as the API review comments were addressed.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Injecting services into ValidationAttributes in ASP.NET Core
This post describes how to use dependency injection with ValidationAttributes in ASP.NET Core, and the process I took in trying to figure ...
Read more >
How to get/inject services in custom ValidationAttributes
My team has heavily invested in our custom validation code which underneath uses DataAnnotations for validation.
Read more >
Resolving IoC container services for Validation Attributes in ...
I'm a fan of the Data Annotation Validation attributes to validate user input on both the client and server side for ASP.
Read more >
Model validation in ASP.NET Core MVC and Razor Pages
Create a class that inherits from ValidationAttribute, and override the IsValid method. The IsValid method accepts an object named value, which ...
Read more >
ASP.NET Core — FluentValidation documentation
With manual validation, you inject the validator into your controller (or api endpoint), invoke the validator and act upon the result.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found