【发布时间】: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