Answer the question
In order to leave comments, you need to log in
How to use async/await in ASP.NET CORE DI container?
Good afternoon!
There is a service:
public interface ISomeService {
Task<Some> GetSomeAsync();
}
services.AddScoped<ISomeService, SomeService>();
services.AddScoped(x => {
var some = await x.GetService<ISomeService>().GetSomeAsync();
});
Answer the question
In order to leave comments, you need to log in
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.
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 questionAsk a Question
731 491 924 answers to any question