1

I'm having this exception:

System.InvalidOperationException: 'Unable to resolve service for type 'System.Collections.Generic.IAsyncEnumerable`1[MyProject.Interfaces.IFooReader]' while attempting to activate 'MyProject.Services.FooService'.'

while trying to resolve IFooService with var fooService = provider.GetRequiredService<IFooService>();.

Here is the FooService class:

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

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

Here is the DI container:

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

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

It looks like the native .net-core DI container does not support injection of IAsyncEnumerable, any way to resolve this?

Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91
  • 2
    Why do you need this as an IAsyncEnumerable? I think the IEnumerable may work fine in this case. – GoodboY Apr 27 '21 at 19:20
  • `IAsyncEnumerable` is not supported. Injecting an `IAsyncEnumerable` makes little sense, as all your `IFooReader` implementations, as they are currently registered, are all constructed synchronously. And DI components shouldn't be loaded asynchronously, because [injection constructors should be simple](https://blog.ploeh.dk/2011/03/03/InjectionConstructorsshouldbesimple/) and you should be able to [compose your object graphs with confidence](https://blog.ploeh.dk/2011/03/04/Composeobjectgraphswithconfidence/). – Steven Apr 27 '21 at 20:51

1 Answers1

1

Use of IEnumerable instead of IAsncEnumerable should resolve this issue.

 public class FooService : IFooService

{
    private readonly IEnumerable<IFooReader> _foosReaders;

    public PriceService(IEnumerable<IFooReader> foosReaders)
    {
        this._foosReaders = foosReaders;            
    }
}
Towhidul Islam Tuhin
  • 1,051
  • 13
  • 10