简体   繁体   中英

.Net core web api configure services before Startup is called

I'm creating .net core 3.1 web api application. By default, it is configured to use IHostBuilder with Startup file which does some configurations

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

I want to add some configurations into my Startup file (events producing) and the problem is that they will not be executed on the application startup but only when api receives the first request. That means that my hosted application won't be able to handle events before it gets a request. So the question is: How can I invoke configuration methods from the Startup file on the application start or how can I do specific configuration that will be executed on the application start?

Use your Program.Main entry point.

Modify this autogenerated code:

public static void Main(string[] args)
{
  CreateHostBuilder(args).Build().Run();
}

To:

public static void Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();

    // Use DI via host.Services:
    var myConfiguredService = host.Services.GetRequiredService<SomeService>();
    myConfiguredService.DoSomething();

    host.Run();
}

That was the preferred way to initialized DB with data in EF 2.0, and still works great for other purposes.

This ( Main ) method runs when dotnet run is executed, before it receives any requests.

But if you host webapp behind IIS be aware that IIS will not actually launch your app until it receives first request! So, you can't solve this problem "inside" your app, and I don't know if new/latest IIS has any settings about this.

Instead, you may use any uptime monitoring service and set it to check your webapp every 1-3-5 minutes, so your webapp will receive some "fake" request and spin up before actual "business" request arrives.

PS If you need async/await - change void Main to async Task Main and host.Run() to await host.RunAsync() (discussed here ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM