更新时间:2022-11-06 17:55:58
您可以从 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();
}