We have a few NSB handlers that are quite latency sensitive, so we would like to ensure that some data is pre-cached in the app that is handling messages before message handling is allowed to begin. Most of this is warm-up/start-up async calls, such as HTTP communication. Our 2 places we have thought of to do this so far are:
- In the same startup flow as where we are registering DI dependencies and starting up the app, before we call
hostBuilder.UseNServiceBus(endpointConfiguration);. The downside being that this context may be non-async, causing us to have to do sync over async. This is likely just an issue of the function we are looking to place it in wasn’t async, but ASP.NET Core supports having an async main, so we should be able to overcome this. - In an IHostedService’s
StartAsync, that whether this warmup IHostedService is registered before or afterhostBuilder.UseNServiceBus(endpointConfiguration);, we think that allIHostedService’s registered should complete theirStartAsyncbefore NSB message handling begins.
We are using ASP.NET core 8, 9, 10 apps with the standard NServiceBus.Extensions.Hosting. Any better suggestions? One thing I am really interested in getting documented is if NSB message handling works the same way as ASP.NET Controller Actions in regard to not starting the processing until all IHostedService StartAsync are completed as documented here.
StartAsync
StartAsync(CancellationToken) contains the logic to start the background task. StartAsync is called before:
-
The app’s request processing pipeline is configured.
-
The server is started and IApplicationLifetime.ApplicationStarted is triggered.
StartAsync should be limited to short running tasks because hosted services are run sequentially, and no further services are started until StartAsync runs to completion.