Using NSB in IHostedService causes error Value cannot be null. (Parameter 'session')

I added NSB v7.3 to ASP.NET Web API’s IHostedService, because I wanted to receive commands and events and have REST api at the same project.
When the IHostedService starts working, I add timer to call a method “DoWork” each 5 seconds, each time the method is called, when I try to use the IMessageSession to publish an event, it throws an exception:

System.AggregateException: One or more errors occurred. (Value cannot be null. (Parameter ‘session’)) —> System.ArgumentNullException: Value cannot be null. (Parameter ‘session’) at NServiceBus.Guard.AgainstNull(String argumentName, Object value) at NServiceBus.IMessageSessionExtensions.Publish(IMessageSession session, Object message)…

Any idea what’s the cause?

I’m using the same idea else where, but I was sure the API service will be receiving a request to one of its Controller before the Publish was called (maybe it’s causing to initiate a session before it’s being used by the IHostedService.
In this new API I’m not sure that a Controller will be called first.


I suspect that you have an ordering issue, can you make sure that the call to UseNServiceBus happens before any call to configure the other services as explained in NServiceBus.Extensions.Hosting • Particular Docs

Let me know if that helps.