在 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();
}