Run async code during startup in a ASP.Net Core application

Henry Zhu

After changing the signature of the function ConfigureServices to be asynchronous (originally it was just a void synchronous function and the application worked perfectly fine), I get the following error:

Unable to find the required services. Please add all the required services by calling IServiceCollection.AddAuthorization inside the call to ConfigureServices(...) in the application startup code.

Below is the code of my ConfigureServices function.

// 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 is automatically called at runtime.

JOSEFtw

You can't just change the signature, it needs to be void to be called by the framework.

Right now when you changed it to Task it means that the framework can't find it so it will not be called at all.

There's a GitHub issue regarding this here: https://github.com/dotnet/aspnetcore/issues/5897

It's quite tricky though...

There's no progress for 5.0 no, we don't know how to do this without blocking or breaking changes. It might be possible to run filters in 2 stages that never overlap.

Update based on your comment: If you want to run something async during startup, I usually do like this:

I create a interface like this:

public interface IStartupTask
{
     Task Execute();
}

Then a sample implementation like this

public class CreateDatabaseStartupTask : IStartupTask
{
    public async Task Execute()
    {
          // My logic here
          // await CreateDatabaseAsync();
    }
}

Then in my 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>();
        });
}

And my Startup

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<IStartupTask, CreateDatabaseStartupTask>();
    }
}

So the important things are:

  1. Register your StartupTasks
  2. Build the host
  3. Resolve the StartupTasks
  4. Run the StartupTasks
  5. Start the Host

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

async call not effectiveness in asp.net core

分類Dev

Redirect user from startup.cs asp.net core

分類Dev

SQL distributed cache created on Asp.net core startup

分類Dev

Path to LocalAppData in ASP.Net Core application

分類Dev

Localizable asp.net core + reactjs application

分類Dev

.NET application (WinForms) depending on ASP.NET Core server

分類Dev

How to submit a file to an ASP.NET Core application

分類Dev

OpenCover for ASP.Net Core application running on IIS Express

分類Dev

ngrok and https tunnel for asp.net core application

分類Dev

How to handle multiple SPA application in ASP.NET Core

分類Dev

Getting Microsoft.AspNetCore.Hosting.Diagnostics[6] Application startup exception in .NET Core 3

分類Dev

config.json Not Being Found on ASP.NET Core Startup in Debug

分類Dev

accessing singleton created within ConfigureServices in the startup.cs file in asp.net core in the same ConfigureServices method

分類Dev

ASP.NET Core return JSON with status code

分類Dev

.Net Core Async File Result

分類Dev

ASP.NET CoreのStartup.csのKestrelシャットダウン関数

分類Dev

ASP.NET CoreのStartup.csのKestrelシャットダウン関数

分類Dev

Run Roslyn analyzers during live code editing but not during build

分類Dev

.NET CoreとASP.NET Core

分類Dev

Is there a way to make a console application run using only a single file in .NET Core?

分類Dev

IIS fails to run ASP.NET Core site - HTTP Error 502.5

分類Dev

IIS fails to run ASP.NET Core site - HTTP Error 502.5

分類Dev

ASP.NET Core、Task.Run()をやり過ぎ?

分類Dev

Run a R Script from asp.net application and get the output from r

分類Dev

Azure WebApp Asp.NET Core 2 error: An error occurred while starting the application

分類Dev

How to host the basic ASP.NET Core 2 WebAPI application on IIS

分類Dev

HTTP Error 502.5 - Process Failure in ASP.NET Core 2.1 application

分類Dev

ASP.Net Core application service only listening to Port 5000 on Ubuntu

分類Dev

ASP.NET Core Fetch POST FormData()application / x-www-form-urlencoded

Related 関連記事

  1. 1

    async call not effectiveness in asp.net core

  2. 2

    Redirect user from startup.cs asp.net core

  3. 3

    SQL distributed cache created on Asp.net core startup

  4. 4

    Path to LocalAppData in ASP.Net Core application

  5. 5

    Localizable asp.net core + reactjs application

  6. 6

    .NET application (WinForms) depending on ASP.NET Core server

  7. 7

    How to submit a file to an ASP.NET Core application

  8. 8

    OpenCover for ASP.Net Core application running on IIS Express

  9. 9

    ngrok and https tunnel for asp.net core application

  10. 10

    How to handle multiple SPA application in ASP.NET Core

  11. 11

    Getting Microsoft.AspNetCore.Hosting.Diagnostics[6] Application startup exception in .NET Core 3

  12. 12

    config.json Not Being Found on ASP.NET Core Startup in Debug

  13. 13

    accessing singleton created within ConfigureServices in the startup.cs file in asp.net core in the same ConfigureServices method

  14. 14

    ASP.NET Core return JSON with status code

  15. 15

    .Net Core Async File Result

  16. 16

    ASP.NET CoreのStartup.csのKestrelシャットダウン関数

  17. 17

    ASP.NET CoreのStartup.csのKestrelシャットダウン関数

  18. 18

    Run Roslyn analyzers during live code editing but not during build

  19. 19

    .NET CoreとASP.NET Core

  20. 20

    Is there a way to make a console application run using only a single file in .NET Core?

  21. 21

    IIS fails to run ASP.NET Core site - HTTP Error 502.5

  22. 22

    IIS fails to run ASP.NET Core site - HTTP Error 502.5

  23. 23

    ASP.NET Core、Task.Run()をやり過ぎ?

  24. 24

    Run a R Script from asp.net application and get the output from r

  25. 25

    Azure WebApp Asp.NET Core 2 error: An error occurred while starting the application

  26. 26

    How to host the basic ASP.NET Core 2 WebAPI application on IIS

  27. 27

    HTTP Error 502.5 - Process Failure in ASP.NET Core 2.1 application

  28. 28

    ASP.Net Core application service only listening to Port 5000 on Ubuntu

  29. 29

    ASP.NET Core Fetch POST FormData()application / x-www-form-urlencoded

ホットタグ

アーカイブ