简体   繁体   中英

Unable to resolve service for type for generic class

I am using FluentValidation and I have created a generic class like so:

public class GenericValidator<T>: AbstractValidator<T>
{
    protected override bool PreValidate(ValidationContext<T> context, ValidationResult result)
    {
        if (context.InstanceToValidate != null) return true;

        result.Errors.Add(new ValidationFailure("model", Resources.NullModelError));

        return false;
    }
}

When I tried to use my application, it returned this error:

System.InvalidOperationException: Unable to resolve service for type 'Api.Controllers.Strategies.StrategyValidator' while attempting to activate 'Api.Controllers.Strategies.Handlers.StrategySaveHandler'.

My StrategyValidator looks like this:

public class StrategyValidator : GenericValidator<StrategyViewModel>
{
    public StrategyValidator()
    {
        RuleFor(model => model.Url).NotEmpty();
    }
}

I have a few of these for different entities and I would like to register them all. I have tried a few ways:

services.AddSingleton(typeof(GenericValidator<>));

services.AddSingleton(typeof(GenericValidator<>), typeof(GenericValidator<>));

services.AddSingleton(typeof(AbstractValidator<>));

services.AddSingleton(typeof(GenericValidator<>), typeof(AbstractValidator<>));

None of them worked. Does anyone know what I can do to register all my validators rather than registering them one by one?

You haven't provided what the service requiring the DI looks like but you could register your validators manually like so: services.AddSingleton(typeof(StrategyValidator))

Additionally you may just want to leverage the generic forms in your services eg instead of requesting a StrategyValidator you should request a GenericValidator<StrategyViewModel>

But generally, Fluent provides an easy way of doing this using their extension methods

eg

services.AddMvc(config =>
{
    config.Filters.Add(new AuthorizeFilter(authorizationPolicy));
}).AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>())

Note: this will register all of the fluent validators that are within the same assembly as Startup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM