简体   繁体   中英

How to get all classes that implement same interface?

I have a design issue. I want to have separate class for every validation. Also, I want to have one class that call all this validations. Idea is that if I need new validation, then I just add new validation class and everything works. I don't need to change anything else, just add new class. Something like this:

    public interface IValidate{
        bool Validate();
    }

    public class Validator1 : IValidate{    
        public bool Validate(){     
            //Do validation 1
        }
    }
    public class Validator2 : IValidate{    
        public bool Validate(){     
            //Do validation 2
        }
    }
    //...
    public class ValidatorN : IValidate{    
        public bool Validate(){     
            //Do validation N
        }
    }
    //...................................
    public interface IValAll{
        bool Validate_All();
    }
    public class ValidateAll : IValAll{
        public bool Validate_All(){     
             //Call all validators that implements IValidate interface
            //Do validation 1,2...N
            //If all validations return true, than this function return true. 
            //Else return false.
        }
    }

I don't know if this is best approach, but you get an idea what I want. Problem is that I don't know how to implement this Validate_All() method.

How to get all classes that implement same interface and do validation in one loop?

Idea is to inject this IValAll interface and do all validation with one call. Also, if you think that my design is not good, please feel free to tell me. I can change approach if someone have better idea.

You can inject all classes implementing IValidate via constructor injection into the class responsible for validating them all:

public class UltimateValidator
{
    private IValidate[] validators

    public UltimateValidator(IValidate[] validators)
    {
         this.validators = validators;
    }

    public bool ValidateAll()
    {
          foreach (var validator in validators)
          {
                 if (validator.Validate())
                 {
                      // etc.
                 }
          }
    }
}

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