【问题标题】:Unable to resolve service for type System.Collections.Generic.IAsyncEnumerable无法解析 System.Collections.Generic.IAsyncEnumerable 类型的服务
【发布时间】:2021-04-27 18:50:50
【问题描述】:

我遇到了这个异常:

System.InvalidOperationException: '无法解析服务类型 'System.Collections.Generic.IAsyncEnumerable`1[MyProject.Interfaces.IFooReader]' 在尝试激活时 'MyProject.Services.FooService'。'

尝试使用var fooService = provider.GetRequiredService<IFooService>(); 解析IFooService。

这是FooService 类:

public class FooService : IFooService
{
    private readonly IAsyncEnumerable<IFooReader> _foosReaders;

    public PriceService(IAsyncEnumerable<IFooReader> foosReaders)
    {
        this._foosReaders = foosReaders;            
    }
}

这是 DI 容器:

services.AddScoped<IFooReader, FooServiceA>(); 
services.AddScoped<IFooReader, FooServiceB>(); 
services.AddScoped<IFooReader, FooServiceC>(); 

services.AddScoped<IFooService, FooService>(); //assuming stateless

原生.net-core DI容器好像不支持IAsyncEnumerable注入,有什么办法解决吗?

【问题讨论】:

  • 为什么需要它作为 IAsyncEnumerable?我认为 IEnumerable 在这种情况下可以正常工作。
  • IAsyncEnumerable 不受支持。注入IAsyncEnumerable 没有什么意义,因为您的所有IFooReader 实现,正如它们当前注册的一样,都是同步构建的。而且DI组件不应该异步加载,因为injection constructors should be simple你应该可以compose your object graphs with confidence。

标签: c# dependency-injection .net-5 iasyncenumerable


【解决方案1】:

使用 IEnumerable 而不是 IAsncEnumerable 应该可以解决此问题。

 public class FooService : IFooService

{
    private readonly IEnumerable<IFooReader> _foosReaders;

    public PriceService(IEnumerable<IFooReader> foosReaders)
    {
        this._foosReaders = foosReaders;            
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 2022-01-10
    • 2020-03-13
    • 2019-02-10
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多