You may need to stop your asp.net core application programmatically
I'm a big fan of open source for countless reasons, which I'll discuss later, but I deliberately started this post with this statement because I believe it's the best time to use programming skills to build something useful. To give an example, I have another post lined up, but that's not the topic for today. In this post, I will share a piece of code that made the complete flow run successfully (again, I will share that later). That's enough for the background, let's jump straight into the sub-section, the piece of code, today's topic, "How to stop an Asp.Net Core application programmatically".
There are different ways, but what I have found most graceful is through IHostApplicationLifetime
interface, which allows developers to control the application's lifetime events. It has a method StopApplication()
, which does the trick and triggers a graceful shutdown. To do so, we need to inject IHostApplicationLifetime
interface in the controller.
// property in any controller
private IHostApplicationLifetime _lifeTime;
// initialize properties in constructor
public AppController(IHostApplicationLifetime lifeTime)
{
_lifeTime = lifeTime;
}
Now the interface is injected, and we can use its method within any action or endpoint in case it's an API.
[HttpGet("StopApplication")]
public IActionResult StopApplication()
{
_lifeTime.StopApplication();
return Ok();
}
How it works
When the endpoint or action is called from within the controller, and hostApplicationLifetime's StopApplication method is called, the application is allowed to clean up any resources in the background services, and the application stops gracefully.