Abhishek Ranjan
Abhishek Ranjan

Reputation: 931

Read from Configuration in Fluent Validators

I am validating my model using Fluent Validation 8.

I want to be able to read from my appsettings.json in my Validator class, but the Configuration is not getting injected.

Here is my validator :

 public class CreateOperationRequestValidator: AbstractValidator<OperationInputModel>
{
    private IConfiguration Configuration { get; set; }
    public CreateOperationRequestValidator(IConfiguration configuration)
    {


        CascadeMode = CascadeMode.StopOnFirstFailure;

        RuleFor(m => m.mode).NotEmpty().IsInEnum();
            ;

    }

But my configuration is null.

My startup is :

 services.AddSingleton<IConfiguration>(Configuration);

        services.AddMvc(opt =>
        {
            opt.Filters.Add(typeof(ValidatorActionFilter));
        }).AddFluentValidation(
            fvc => fvc.RegisterValidatorsFromAssemblyContaining<Startup>()
        );

Upvotes: 2

Views: 2195

Answers (2)

Paresh
Paresh

Reputation: 138

You can do something like this

Create a ConfigSettings modal class with your required properties

public class ConfigSettings
{
   // get and set your setting properties here 
}

Then pass settings like below in your validator constructor parameter using Microsoft.Extensions.Options

public class CreateOperationRequestValidator: AbstractValidator<OperationInputModel>
{
    public CreateOperationRequestValidator(IOptions<ConfigSettings> settings)
    {


        CascadeMode = CascadeMode.StopOnFirstFailure;

        RuleFor(m => m.mode).NotEmpty().IsInEnum();
            ;

    }
}

You can access the properties by doing settings.Value.{your property name}

Lastly add following lines in Startup.cs

public void ConfigureServices(IServiceCollection services)
{
     services.AddOptions();
     services.Configure<ConfigSettings>(Configuration);
     services.Add(ServiceDescriptor.Transient(typeof(ConfigSettings), typeof(ConfigSettings)));

}

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239290

In order for classes to be injected, those classes must themselves be registered with the service collection. It's very likely that Fluent Validation is not doing so, and as a result, there's nothing you can do. In other words, you're at the mercy of the library itself here, and how it handles object instantiation and lifetimes internally.

It's worth mentioning as well that attributes cannot be injected into because they're essentially instantiated in place. This is a limitation of attributes in general, not just Microsoft.Extensions.DependencyInjection. I'm not sure if you're using the filters as attributes or not, but it's exceedingly likely that Fluent Validation does not support injection here, simply because it would not be consistent depending on the use case.

Upvotes: 1

Related Questions