Vaughan Reid's blog

ASP.Net Core Hosted services

In the containerized application and Kubernetes world, quite often you need to create services that aren't traditional rest endpoints. Your application could for example rather listen to a message queue to process requests. It would be nice to still have all the nice infrastructure of .NET Core applications and things like health checks but have it work closer to a windows service.

Now you can do this quite easily with the Hosted services. You can define a class that will execute work when the application starts up independently of any web requests. To do this all you need to do is create a class that implements the BackgroundService abstract base class. A really simple example:


public class MyHostedService : BackgroundService
{
	private readonly IMessageQueue messageQueue;

	public MyHostedService(IMessageQueue messageQueue)
	{
		this.messageQueue = messageQueue;
	}

	public override Task StartAsync(CancellationToken cancellationToken)
	{
		return base.StartAsync(cancellationToken);
	}
	
	public override Task StopAsync(CancellationToken cancellationToken)
	{
		return base.StopAsync(cancellationToken);
	}

	protected override async Task ExecuteAsync(CancellationToken stoppingToken)
	{
		while (messageQueue.IsConnected)
		{
			(bool received, string message) = await messageQueue.Get();
			
			if (received)
			{
				//do something
			}
			await Task.Delay(TimeSpan.FromSeconds(1));
		}

	}
}

Then all you need to do for this to start when the application runs is to register it in the Startup.cs ConfigureServices is to add:


services.AddHostedService<MyHostedService>();

You could also implement the start and stop methods of the IHostedService but in general you need to be careful in how you do it because you could cause the whole application startup to delay.