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.
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?
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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With