更新时间:2022-11-06 16:50:43
您可以在 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();
}