Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call async method in AddTransient in Startup - Asp.Net Core

I have a service which is used to get some information and the method has a bunch of async calls in the chain.

public interface IFooService
{
    Task<IFoo> GetFooAsync();
}

The concrete class,

public class FooService : IFooService
{
    public async Task<IFoo> GetFooAsync()
    {
        // whole bunch of awaits on async calls and return IFoo at last
    }
}

I register this service on StartUp,

services.AddTransient<IFooService, FooService>();

Several other services are injected with this service. One among them,

public class BarService : IBarService
{
    private readonly IFooService _fooService;

    public BarService(IFooService fooService)
    {
        _fooService = fooService;
    }

    public async Task<IBar> GetBarAsync()
    {
        var foo = await _fooService.GetFooAsync();

        // additional calls & processing
        var bar = SomeOtherMethod(foo);

        return bar;
    }
}

IFoo is integral to the application and used across several services. Most of my code is async just due to this one IFooService and the one method it has which returns IFoo.

Considering this use case, I would like to be able to just inject IFoo to all other services as opposed to injecting them with IFooService.

I gave this a shot,

services.AddTransient<IFoo>(provider => 
{
    var fooService = provider.GetService<IFooService>();
    var foo = fooService.GetFooAsync().GetAwaiter().GetResult();
    return foo;
});

but it raises a red flag to me as I'm doing sync over async and I'm unsure if this will cause any issues like race conditions. Would startup be blocked by doing this. Im looking for a clean way to handle this, any recommendation for when we need something like this? Thank you for your help.

like image 259
Emmanuel Ponnudurai Avatar asked Jan 31 '26 16:01

Emmanuel Ponnudurai


1 Answers

Your code is not bad , but can use folowing code :

services.AddTransient<Task<IFoo>>(provider => 
{
    var fooService = provider.GetService<IFooService>();
    return fooService.GetFooAsync();
});

can use its for example following code :

var foo = await HttpContext.RequestServices.GetService<Task<IFoo>>();

If you want to run code when creating the IFoo , you can use the following code:

var fooTask = HttpContext.RequestServices.GetService<Task<IFoo>>();
/*your Code*/
var foo = await fooTask; /* OR var foo = fooTask.GetAwaiter().GetResult()*/
like image 64
BQF Avatar answered Feb 02 '26 05:02

BQF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!