I would like to test certain conditions on Startup of my ASP.Net Core 2.0 application. For example if my database server or other is running correctly. This is especially helpful for things that will only be instantiated after a request (like my repository).
Currently I have to do this request manually, but I would like to have my application fail early. At what moment and in what place is such a test recommended?
The
Startup
class is responsible for setting up your server, making it the perfect candidate for setting up one-time initialization stuff for your application.You usually have two main methods in
Startup
:ConfigureServices
andConfigure
. The former runs very early and is responsible for setting up the application services, dependencies and configuration. So you cannot use it to actually perform real work, especially since the dependency injection container is not ready yet.However, the
Configure
method is different: While its main purpose is to set up the application middleware pipeline, the components that will later serve requests, you are able to fully use your dependencies here, making it possible to already do more extensive things here. So you could make your calls directly here.It’s important to understand that
Configure
still runs rather early, way before your server is actually ready to serve requests. So if your initialization depends on the actual server being around already, you should probably further delay the execution.The proper solution is likely to hook into the application lifecycle using
IApplicationLifetime
. This type basically offers you a way to register callbacks that are executed during the application lifecycle. In your case, you would be interested in theApplicationStarted
event which runs when the server just completed its setup phase and is now ready to serve requests. So basically the perfect idle moment to run some additional initialization.In order to respond to a lifetime event, you need to register your handler inside the
Configure
method:One final note: Apparently, there is currently an open bug that prevents lifetime events from firing when hosting on IIS. In that case, executing your code directly in
Configure
is probably the best alternative.