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:

1
2
3
4
public interface IValidationRule
{
   public bool IsValid(object data);
}

The two classes implementing the interface:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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:

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

The injection of the implementations in a third class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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