Lazy<IMessageSession> Not Initialised After Endpoint Startup

We have a ASP.Net Core 2.2 application using the built in IoC container that is using the IStartableEndpointWithExternallyManagedContainer interface, and we are using RabbitMQ as our underlying transport. We have other applications using exactly the same set up, but we are hitting an issue whereby on one specific environment where we get the following error when trying to resolve and use the lazy message session:

Failed to Send PersistReply command with Reply 6b18e49d-3749-4ddf-ab22-a2e1a5d343d6 for message with Transaction be2318a6-5306-4300-a02e-e7fc7ff2b87a to the service bus, encountered exception: System.InvalidOperationException: The message session can only be used after the endpoint is started.
at NServiceBus.StartableEndpointWithExternallyManagedContainer.<.ctor>b__0_0()
at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)

There is nothing logged to indicate that the IStartableEndpointWithExternallyManagedContainer.Start fails (we definitely await the async start method), and we have added logging directly after the endpoint start call so we know that it is getting past this point. We can also see NServiceBus debug that states:

Receiver "Main" is starting, listening to queue ....

We suspect it is something environmental that is causing a startup failure, but we’re struggling to see anything in the logs that would point us to the failure, and we’re perplexed as to why the endpoint is showing as successfully started up but then it shows as not started when we try to use the message session.

Do you have any advice on how we could further diagnose the issue?


There are some known race conditions in the way netcore 2.2 starts when using the WebHostBuilder. Can you share the code you use to set up the endpoint?

I’d recommend that you use which has code to avoid the race condition if going to the GenericHost and netcore3.0 isn’t an option.

Did you get this sorted out @Ross ?

Hi @andreasohlund . Apologies for the late reply. The team that were hitting this issue have shelved the NServiceBus integration for now due to some other ongoing priorities, and they never got round to trying your suggestions, so feel free to close this one off as not required. If they hit the issue again then I’ll just get them to start a new discussion on it.