Skip to content

Wire up IServiceProvider when validating DataAnnotations attributes on Options #36009

@akilin

Description

@akilin

Describe the bug

App was unable to resolve IWebHostEnvironment from ValidationContext when validating options with custom Required attribute inside Configure method.

To Reproduce

IWebHostEnvironment not resolving, when trying to create a custom validation attribute to make something required only in Production environment.

Relevant code snippets

    public class DemoOptions
    {
        [RequiredInProd]
        public string FooBar { get; set; }
    }

    public class RequiredInProd : RequiredAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            //this errors
            var env = validationContext.GetRequiredService<IWebHostEnvironment>();
            return ValidationResult.Success;
        }
    }
//Startup.cs methods
public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions<DemoOptions>()
                .Bind(Configuration.GetSection(nameof(DemoOptions)))
                .ValidateDataAnnotations();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //this line works fine and IWebHostEnvironment is resolved.
            var envFromServices = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>();
            //this errors when trying to resolve IWebHostEnvironment inside Attribute methods
            _ = app.ApplicationServices.GetRequiredService<IOptions<DemoOptions>>().Value;
        }

-->

Metadata

Metadata

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions