Search code examples
c#asp.net-web-apidependency-injectionunity-containerfluentvalidation

How to register all validators generically


I have a problem with dependency injection using open generic types.

To register a validator now, I must write:

container.RegisterType<IValidator<User>, UserValidator>();

I need something like this:

container.RegisterType(typeof(IValidator<>), typeof(Validator<>));

where UserValidator class is

 public class UserValidator : Validator<User>
 {
        public UserValidator()
        {
            RuleFor(user => user.Email).EmailAddress();
        }
 }

Solution

  • Unity Container does support registration of open generics (here's an example of someone doing that), but you are wanting mappings to concrete, non-generic classes. The built in functionality will resolve an open generic interface to a closed generic class.

    Your attempted registration

    container.RegisterType(typeof(IValidator<>), typeof(Validator<>));
    

    will resolve to a Validator<User>, which you clearly don't want. There's no way using the built in functionality to tell it "I really want you to resolve to the non-generic subclass of Validator<User>".

    What I suggest instead is that you create an extension method on IUnityContainer that will reflect over the assembly looking for non-generic validators, and register those individually.