ASP.NET Core中的应用程序启动代码 [英] Application startup code in ASP.NET Core

查看:231
本文介绍了ASP.NET Core中的应用程序启动代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读 ASP.NET Core文档,其中有有两种启动方法:Configure和ConfigureServices.

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?

推荐答案

在启动时,此类自定义代码基本上有两个入口点.

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

1.) Main 方法

1.) Main method

由于ASP.NET Core应用程序具有良好的旧 Main 方法作为入口点,因此可以将代码放在ASP.NET Core启动内容之前,例如

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.)使用您的 Startup

2.) Use your Startup class

正如您在问题中已经提到的那样, Configure ConfigureServices 是自定义代码的好地方.

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

我希望使用 Startup 类.从运行时的角度来看,这是无关紧要的,无论是在启动时还是在 host.Run()调用之前的其他位置调用此调用.但是,从习惯于ASP.NET框架的程序员的角度来看,他对这种逻辑的第一个外观是 Startup.cs 文件.所有示例和模板都在其中放置了标识,实体框架初始化等的逻辑.因此,按照惯例,我建议将初始化内容放在此处.

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.

这篇关于ASP.NET Core中的应用程序启动代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆