Shutdown - DI removes my objects?

Hi, we need some insight and suggestions.

We just had some issues with objects suddenly being NULL after/during a shutdown. After some debugging we suspect that what has happened is that ServiceStack (or ASP.net core?) is emptying the DI-container, in which there are objects that we use, while our service was running.

In one case, in the middle of a service code, AppHost was null. But there are many more examples.

I would think that a “graceful shutdown” would let our services finish before something like this might happen, and not let any new service call be started. Is there a mechanism like that? It could be that our service took too long to finish (what is too long). What could be the cause, and more importantly how can we prevent problems? I can’t reasonably have an if-test on every second line, before using my objects…

The shutdown behavior is determined by the Host (i.e. ASP .NET Core), we don’t get to control the behavior of the host only start the cleanup and dispose all disposable dependencies. ASP .NET Core shouldn’t be sending new requests through after a shutdown has been initiated, so I’m assuming the issue is with your long running Services. How you handle it is up to you, e.g. if it’s processing in a loop check if the AppHost is disposed and throw a cancellation or disposed Exception.

You can override ServiceStack’s built-in behavior by overriding void Dispose(bool disposing) in your AppHost. You can check whether the AppHost is disposed from appHost.IsDisposed also accessible via singleton HostContext.AppHost.IsDisposed.

You can also register a shutdown callback directly with the host:

var appLifetime = app.ApplicationServices.GetService<IHostApplicationLifetime>();
appLifetime?.ApplicationStopping.Register(OnApplicationStopping);

This is what we use to get notified the App is shutting down.

1 Like