Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core dependency injection -> Get all implementations of an interface

Tags:

I have a interface called IRule and multiple classes that implement this interface. I want to uses the .NET Core dependency injection Container to load all implementation of IRule, so all implemented rules.

Unfortunately I can't make this work. I know I can inject an IEnumerable<IRule> into my ctor of the controller, but I don't know how to register this setup in the Startup.cs

like image 927
Nik Avatar asked Sep 19 '16 07:09

Nik


People also ask

CAN interface have multiple implementations C#?

Explicit interface implementation also allows the programmer to implement two interfaces that have the same member names and give each interface member a separate implementation.

Does .NET Core have dependency injection?

ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core.

What is AddScoped in .NET Core?

AddScoped() - This method creates a Scoped service. A new instance of a Scoped service is created once per request within the scope. For example, in a web application it creates 1 instance per each http request but uses the same instance in the other calls within that same web request.

What is IServiceCollection in .NET Core?

AddScoped(IServiceCollection, Type, Type) Adds a scoped service of the type specified in serviceType with an implementation of the type specified in implementationType to the specified IServiceCollection.


1 Answers

It's just a matter of registering all IRule implementations one by one; the Microsoft.Extensions.DependencyInjection (MS.DI) library can resolve it as an IEnumerable<T>. For instance:

services.AddTransient<IRule, Rule1>();
services.AddTransient<IRule, Rule2>();
services.AddTransient<IRule, Rule3>();
services.AddTransient<IRule, Rule4>();

Consumer:

public sealed class Consumer
{
    private readonly IEnumerable<IRule> rules;

    public Consumer(IEnumerable<IRule> rules)
    {
        this.rules = rules;
    }
}

NOTE: The only collection type that MS.DI supports is IEnumerable<T>.

like image 130
Steven Avatar answered Sep 27 '22 20:09

Steven