Search code examples
c#asp.net-coredependency-injection.net-corefluentvalidation

.NetCore Create Default FluentValidator for all Types


I'm trying to have .Net Cores' dependency injector use a default validator for all created new Service types.

My startup looks like this:

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

and my Default Validator looks like this:

public class DefaultValidator<TEntity> : AbstractValidator<TEntity>
{
}

It's really annoying having to register the validator for every new service I create, I would like to use the default one for any unknown registered type.

I know it can be view as semi dangerous but this is for testing purposes and I can have it throw if it's on production so thats not an issue.

How can I register a default Validator with .Net Core's Dependency Injector?


Solution

  • You should be able to register using open generics like in this example

    services.AddScoped(typeof(IValidator<>), typeof(DefaultValidator<>));