.Net 6.0, EF, Asp.Net Core
I'm trying to interrupt my web server's startup if the connection to the db could not be established. I'm thinking that the natural place to insert the test is at the end of the Configure method in startup.cs.
I've found a lot of questions about that in stackoverflow but most of the time they don't address my situation :
I've been trying to address it this way :
But to do so, I need to get an instance of the DbContext first. I tried to do a quick "local" dependency injection the usual way :
var dbcontext = app.ApplicationServices.GetRequiredService<IDbContext>();
Problem : this fails at runtime because of the scope of Dbcontext. Apparently, only singletons can be injected in method "Configure". It's too early in the application's lifecyle to instantiate other scopes.
Out of desperation, I tried to create a Singleton service just for that, which in turn would receive the IDbContext in its contructor. Same issue : .Net's validation round detects that there's something fishy with the pyramid of scopes and throws an Exception.
So how do you get one instance of your DbContext as early as startup, or more generally how do you test the connection to your database as early as startup?
more generally how do you test the connection to your database as early as startup?
It's really simple: don't use DI. Create an instance of your DbContext using a constructor that takes a connection string.