W
W
WhiteNinja2018-08-07 19:23:01
ASP.NET
WhiteNinja, 2018-08-07 19:23:01

How to use async/await in ASP.NET CORE DI container?

Good afternoon!
There is a service:

public interface ISomeService {
  Task<Some> GetSomeAsync();
}

In this case, you need to add the result of the GetSomeAsync method to the DI container, i.e. Some.
It turns out the following:
services.AddScoped<ISomeService, SomeService>();
services.AddScoped(x => {
  var some = await x.GetService<ISomeService>().GetSomeAsync();
});

Accordingly, the second AddScoped gives a compiler error, since there is no async. If you add async x => then the compiler does not swear, but the solution does not work. The application cannot resolve Some.
A huge request to suggest how to add a call to the GetSomeAsync () method through the provider?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
basrach, 2018-08-08
@basrach

Look at the signature of the second call to AddScoped. In Visual Studio, this can be done by hovering over the method.
It will be like this: AddScoped>(x => ... That is, not Some, but Task is registered in the container. And this is normal, the asynchronous method always returns Task. To register Some, you need the lambda inside AddScoped to be synchronous, this can be achieve by writing either ...GetSomeAsync().Result, or somehow get the result, and directly return it already.

A
Artemka95, 2018-09-02
@Artemka95

And it should definitely be at the DI level?
In my opinion, something is wrong in the logic here if the result of an asynchronous operation needs to be resolved from the container.
In any case, you can try to register not Some but Func> and resolve it specifically.
Standard DI container supports this option

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question