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
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.
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.
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.
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.
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With