在ASP.NET Core中将应用程序启动逻辑放在何处 [英] Where to put application startup logic in ASP.NET Core

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

问题描述

我想用ASP.NET Core 2.1创建一个Web服务,该服务在应用程序启动时检查与数据库的连接是否有效,然后在数据库中准备一些数据.

I want to create a web service with ASP.NET Core 2.1 which checks on application startup if the connection to the database works and then prepares some data in the database.

检查将循环运行,直到连接成功或用户按Ctrl + C( IApplicationLifetime ).在初始化数据库之前,请勿处理任何HTTP调用,这一点很重要.我的问题是:将此代码放在哪里?

The check runs in a loop till the connection was successful or the users presses Ctrl + C (IApplicationLifetime). It is important that no HTTP call is processed before the database was initialized. My question is: where to put this code?

我需要完全初始化依赖项注入系统,因此我可以想到的最早是在我的 Startup.Configure 方法的末尾,但是 IApplicationLifetime上的取消标记似乎在那里不起作用(正确的原因是asp尚未完全启动)

I need a the dependency injection system to be fully initialized, so the earliest i can think of would be at the end of my Startup.Configure method, but the cancellation tokens on IApplicationLifetime do not seem to work there (properly because asp isn't fully started)

在正式场所可以放置此启动逻辑吗?

Is there a official place where can put this startup logic?

推荐答案

您可以在 IWebHost 的基础上构建扩展方法,该方法可让您在 Startup.cs 之前运行代码>.此外,您可以使用 ServiceScopeFactory 初始化您拥有的任何服务(例如 DbContext ).

You can build an extension method off of IWebHost which will allow you to run code before Startup.cs. Furthermore, you can use the ServiceScopeFactory to initialize any services you have (e.g. DbContext).

public static IWebHost CheckDatabase(this IWebHost webHost)
{
    var serviceScopeFactory = (IServiceScopeFactory)webHost.Services.GetService(typeof(IServiceScopeFactory));

    using (var scope = serviceScopeFactory.CreateScope())
    {
        var services = scope.ServiceProvider;
        var dbContext = services.GetRequiredService<YourDbContext>();

        while(true)
        {
            if(dbContext.Database.Exists())
            {
                break;
            }
        }
    }

    return webHost;
}

然后您就可以使用该方法了.

Then you can consume the method.

public static void Main(string[] args)
{
    BuildWebHost(args)
        .CheckDatabase()
        .Run();
}

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

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