在 ASP.Net Core 应用程序启动期间运行异步代码

Posted

技术标签:

【中文标题】在 ASP.Net Core 应用程序启动期间运行异步代码【英文标题】:Run async code during startup in a ASP.Net Core application 【发布时间】:2020-11-29 01:18:43 【问题描述】:

在将函数ConfigureServices 的签名更改为异步后(最初它只是一个无效的同步函数,应用程序运行良好),我收到以下错误:

找不到所需的服务。请通过在应用程序启动代码中对ConfigureServices(...) 的调用中调用IServiceCollection.AddAuthorization 添加所有必需的服务。

下面是我的ConfigureServices函数的代码。

// This method gets called by the runtime. Use this method to add services to the container.
public async Task ConfigureServices(IServiceCollection services)

    services.AddRazorPages();

    // Create the necessary Cosmos DB infrastructure
    await CreateDatabaseAsync();
    await CreateContainerAsync();

ConfigureServices 在运行时自动调用。

【问题讨论】:

有可能使用 IHostedService ***.com/a/64118183/940182 【参考方案1】:

您不能只更改签名,它需要被框架调用。

现在当你把它改成 Task 时,意味着框架找不到它,所以它根本不会被调用。

这里有一个 GitHub 问题:https://github.com/dotnet/aspnetcore/issues/5897

这很棘手......

5.0 没有任何进展,我们不知道如何在不阻止或破坏更改的情况下做到这一点。有可能在两个永不重叠的阶段运行过滤器。

根据您的评论更新: 如果你想在启动过程中异步运行,我通常会这样做:

我创建一个这样的界面:

public interface IStartupTask

     Task Execute();

然后是这样的示例实现

public class CreateDatabaseStartupTask : IStartupTask

    public async Task Execute()
    
          // My logic here
          // await CreateDatabaseAsync();
    

然后在我的 Program.cs 中

public static async Task Main(string[] args)

    var host = CreateHostBuilder(args).Build();
    
    // Resolve the StartupTasks from the ServiceProvider
    var startupTasks = host.Services.GetServices<IStartupTask>();
    
    // Run the StartupTasks
    foreach(var startupTask in startupTasks)
    
        await startupTask.Execute();
    
    await host.RunAsync();


public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        
            webBuilder.UseStartup<Startup>();
        );

还有我的创业公司

public class Startup

    public void ConfigureServices(IServiceCollection services)
    
        services.AddTransient<IStartupTask, CreateDatabaseStartupTask>();
    

所以重要的是:

    注册您的 StartupTasks 构建主机 解决 StartupTasks 运行 StartupTasks 启动主机

【讨论】:

那么如何在启动时调用异步函数(CreateDatabaseAsync 和 CreateContainerAsync)? 用例子更新了我的答案 这很棒 - 一定要试试这个

以上是关于在 ASP.Net Core 应用程序启动期间运行异步代码的主要内容,如果未能解决你的问题,请参考以下文章