We have an ASP.NET core startup class. In the constructor we perform a back-end database call with some initialization. If this fails and an exception is thrown the ASP.NET core application gives the message 'An exception has occured while starting the application'.
We would like the system to perform the startup again on subsequent requests.
Is this possible?
You shouldn’t do any logic inside of the Startup constructor. If you want to perform some action at the beginning of your application, before the server actually starts, then you should do that at the WebHost level.
By default, the Main in Program.cs looks like this:
CreateWebHostBuilder(args).Build().Run();
You can easily split this up and do something before you call Run():
var webHost = CreateWebHostBuilder(args).Build();
// do something here
// if necessary, repeat that until it works, and then launch the server
webHost.Run();
Since the web host is already built, you can even access your server’s services at that point already. For example, this pattern is commonly used to initialize the database using an Entity Framework datbase context. That would look like this:
var webHost = CreateWebHostBuilder(args).Build();
using (var scope = webHost.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<MyDataContext>();
// create the database, add some data, etc.
db.Database.EnsureCreated();
}
webHost.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