Async provider in .net core DI

I'm just wondering if it's possible to have async/awaitduring DI.

By doing the following, DI cannot enable my service.

services.AddScoped(async provider => 
{
  var client = new MyClient();
  await client.ConnectAsync();
  return client;
});

where, since the following works fine.

services.AddScoped(provider => 
{
  var client = new MyClient();
  client.ConnectAsync().Wait();
  return client;
});
+11
source share
1 answer

Async / await does not make sense when resolving dependencies, because:

This means that everything related to input / output should be delayed until a graph of objects is built.

, MyClient, MyClient , .

UPDATE

MyClient , , , , " [s], ".

, , :

/

, , , . Composition Root , .

, API, , , .

, :

public interface IMyAppService
{
    Task<Data> GetData();
    Task SendData(Data data);
}

, ConnectAsync; . , , :

public sealed class MyClientAdapter : IMyAppService,
    IDisposable
{
    private readonly Lazy<Task<MyClient>> connectedClient;

    public MyClientAdapter()
    {
        this.connectedClient = new Lazy<Task<MyClient>>(async () =>
        {
            var client = new MyClient();
            await client.ConnectAsync();
            return client;
        });
    }

    public async Task<Data> GetData()
    {
        var client = await this.connectedClient.Value;
        return await client.GetData();
    }

    public async Task SendData(Data data)
    {
        var client = await this.connectedClient.Value;
        await client.SendData(data);
    }

    public void Dispose()
    {
        if (this.connectedClient.IsValueCreated)
        {
            this.connectedClient.Value.Dispose();
        }
    }
}

. MyClient Lazy<T>, , , GetData SendData, .

IMyAppService MyClient MyClientAdapter IMyAppService .

+17

Source: https://habr.com/ru/post/1674140/


All Articles