使用依赖注入在控制器中注入 IEnumerable 接口

Aks*_*iti 7 c# dependency-injection .net-core asp.net-core-5.0

我想解决继承控制器上的接口的多个类的 IEnumerable 集合的依赖关系。

我想在应用程序启动期间解决以下依赖关系:

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

通知策略

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

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

在 ASP.NET Core 中,在不使用任何外部依赖项或库的情况下,对 IEnumerable 类型的对象进行依赖项注入的最佳方式是什么?

Nko*_*osi 11

在复合根处向服务集合注册所有类型

//...

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

services.AddScoped<INotificatonStrategy, NotificationStrategy>();

//...
Run Code Online (Sandbox Code Playgroud)

并且在解析所需类型时应注入所有依赖项,因为构造函数已经具有IEnumerable<INotificationService>构造函数参数

参考ASP.NET Core 中的依赖注入