小编Emm*_*rai的帖子

在启动时调用 AddTransient 中的异步方法 - Asp.Net Core

我有一个用于获取一些信息的服务,并且该方法在链中有一堆异步调用。

public interface IFooService
{
    Task<IFoo> GetFooAsync();
}
Run Code Online (Sandbox Code Playgroud)

具体类,

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

我在 StartUp 上注册了这个服务,

services.AddTransient<IFooService, FooService>();
Run Code Online (Sandbox Code Playgroud)

此服务注入了其他几个服务。其中之一,

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; …
Run Code Online (Sandbox Code Playgroud)

c# startup async-await asp.net-core

6
推荐指数
1
解决办法
2573
查看次数

标签 统计

asp.net-core ×1

async-await ×1

c# ×1

startup ×1