Jerry Nixon @Work: Waiting for Kestral

Jerry Nixon on Windows

Tuesday, October 25, 2022

Waiting for Kestral

Kestrel is the ASP.NET Core web server. You can call its endpoints only after it has started. Using the IHostApplicationLifetime interface, you can register a callback for when the server starts & stops. This prevents workarounds like Wait() or Sleep() or Delay() that, honestly, we have all tried. The callback is nice and clean and is deterministic and reliable. 

Let's look at the IHostApplicationLifetime interface.

The IHostApplicationLifetime service is available to you from the service provider. Once you have it you register callbacks to call the host without fear the server is not yet ready. 

Knowing you can get IHostApplicationLifetime from the services collection is useful, but if you have local access to the WebApplicationinstance, you can access the same from the Lifetime property

For a demo hosting and calling a minimal API from a single project - this is nice. But in the real world, access to the local instance of WebApplication is unlikely. In those cases, solve it with a retry policy. 

Best of luck!