Skip to content
This repository was archived by the owner on Dec 14, 2025. It is now read-only.
This repository was archived by the owner on Dec 14, 2025. It is now read-only.

Validation via data annotations does not support dependency injection / resolution #157

@reddogaw

Description

@reddogaw

In a custom data annotation, the ValidationContext typically supports acting as an IServiceProvider to resolve dependencies required for the validation action.

This support is typically provided by the ValidationContext constructor overload which allows you to pass the IServiceProvider used by the application. However, that's currently not being passed by Cocona, so it's leading to unregistered dependency exceptions when resolving within a custom validation attribute's IsValid method.

Example which is silly but indicative:

    class IsEvenUsingDependencyInjectionAttribute : ValidationAttribute
    {
        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {
            if (value is not int number)
            {
                return new ValidationResult($"Could not validate value, values's type is {value?.GetType()}");
            }
            
            var calculator = validationContext.GetRequiredService<Calculator>();
            return calculator.IsEven(number)
                ? ValidationResult.Success
                : new ValidationResult("Value is an uneven number.");
        }
    }
    
    class Calculator
    {
        public bool IsEven(int number) => number % 2 == 0;
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions