Application startup code in ASP.NET Core

亡梦爱人 提交于 2020-12-02 00:16:44

问题


Reading over the documentation for ASP.NET Core, there are two methods singled out for Startup: Configure and ConfigureServices.

Neither of these seemed like a good place to put custom code that I would like to run at startup. Perhaps I want to add a custom field to my DB if it doesn't exist, check for a specific file, seed some data into my database, etc. Code that I want to run once, just at app start.

Is there a preferred/recommended approach for going about doing this?


回答1:


Basically there are two entry points for such custom code at startup time.

1.) Main method

As a ASP.NET Core application has got the good old Main method as entry point you could place code before the ASP.NET Core startup stuff, like

public class Program
{
    public static void Main(string[] args)
    {
        // call custom startup logic here
        AppInitializer.Startup();

        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}

2.) Use your Startup class

As you already stated in your question is the Configure and ConfigureServices a good place for your custom code.

I would prefer the Startup class. From the runtime perspective it does not matter, if the call is called in startup or somewhere else before the host.Run() call. But from a programmer's point of view who is accustomed to the ASP.NET framework then his first look for such logic would be the Startup.cs file. All samples and templates put there the logic for Identity, Entity Framework initialization and so on. So as a convention I recommend to place the initialization stuff there.




回答2:


I agree with the OP.

My scenario is that I want to register a microservice with a service registry but have no way of knowing what the endpoint is until the microservice is running.

I feel that both the Configure and ConfigureServices methods are not ideal because neither were designed to carry out this kind of processing.

Another scenario would be wanting to warm up the caches, which again is something we might want to do.

There are several alternatives to the accepted answer:

  • Create another application which carries out the updates outside of your website, such as a deployment tool, which applies the database updates programmatically before starting the website

  • In your Startup class, use a static constructor to ensure the website is ready to be started

Update

The best thing to do in my opinion is to use the IApplicationLifetime interface like so:

public class Startup
{
    public void Configure(IApplicationLifetime lifetime)
    {
        lifetime.ApplicationStarted.Register(OnApplicationStarted);
    }

    public void OnApplicationStarted()
    {
        // Carry out your initialisation.
    }
}



回答3:


This can be done by creating an IHostedService implementation and registering it using IServiceCollection.AddHostedService<>() in ConfigureServices() in your startup class.

Example

using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;

public class MyInitializer : IHostedService
{
    public Task StartAsync(CancellationToken cancellationToken)
    {
        // Do your startup work here

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        // We have to implement this method too, because it is in the interface

        return Task.CompletedTask;
    }
}
using Microsoft.Extensions.DependencyInjection;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHostedService<MyInitializer>();
    }
}

Notes

  • The main application will not be started until after your code has finished executing.
  • Constructor dependency injection is available to the IHostedService implementation.
  • I can recommend this blog post for more info, and an example of how to use async: https://andrewlock.net/running-async-tasks-on-app-startup-in-asp-net-core-3/
  • For more background reading, see this discussion: https://github.com/dotnet/aspnetcore/issues/10137


来源:https://stackoverflow.com/questions/39047229/application-startup-code-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!