How to register and inject multiple implementations of one interface in .NET

There are times when you want to register multiple classes which all implement a common interface. One example could be a IValidationRule interface which is implemented by different validation rules, lets say NameNotEmptyValidationRule and the NameRangeValidationRule. We want these rules to run in order and validate user input. Let’s see this example in form of code:

The IValidationRule interface:

public interface IValidationRule
{
   public bool IsValid(object data);
}

The two classes implementing the interface:

public class NameNotEmptyValidationRule : IValidationRule
{
   public bool IsValid(object data)
   {
       return !string.IsNullOrEmpty((string)data);
   }
}

public class NameRangeValidationRule : IValidationRule
{
   public bool IsValid(object data)
   {
       return (string)data <= 40;
   }
}

The registration of the two classes in Program.cs of our .NET Core project:

services.AddTransient<IValidationRule, AgeValidationRule>();
services.AddTransient<IValidationRule, NameValidationRule>();

The injection of the implementations in a third class:

public class ValidationController
{
    private readonly IEnumerable<IValidationRule> rules;

    public ValidationController(IEnumerable<IValidationRule> rules)
    {
        this.rules = rules;
    }

    public void Validate()
    {
        foreach(IValidationRule rule in rules)
        {
            // Do something with each IsValid Method
        }
    }
}

Check how we use the IEnumerable to inject all the registered implementations in the constructor of the controller.

comments powered by Disqus