简体   繁体   中英

Inject an IEnumerable of interface in controller using Dependency Injection

I want to resolve the dependency for the IEnumerable collections of the multiple class inheriting the Interface on the controller .

I want to resolve the following dependency during the application startup:

var notificationStrategy = new NotificationStrategy(
new INotificationService[]
{
    new TextNotificationService(), // <-- inject any dependencies here
    new EmailNotificationService()      // <-- inject any dependencies here
});

NotificationStragey

public class NotificationStrategy : INotificatonStrategy
{
    private readonly IEnumerable<INotificationService> notificationServices;

    public NotificationStrategy(IEnumerable<INotificationService> notificationServices)
    {
        this.notificationServices = notificationServices ?? throw new ArgumentNullException(nameof(notificationServices));
    }
}

What is the best way of dependency injection of IEnumerable types of objects in the asp.net core without using any external dependency or library?

Register all the types with the service collection at the composite root

//...

services.AddScoped<INotificationService, TextNotificationService>();
services.AddScoped<INotificationService, EmailNotificationService>();

services.AddScoped<INotificatonStrategy, NotificationStrategy>();

//...

and all dependencies should be injected when resolving the desired type since the constructor already has IEnumerable<INotificationService> as a constructor parameter

Reference Dependency injection in ASP.NET Core

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