Generic hosted services in .NET Core using IHost and IHostedService

An approach used to simulate a long running or permanently running background task for cloud services is to deploy a REST API, and to invoke end-points on the API from a cloud-native event handler (AWS Lambdas or Azure Functions). When migrating on-prem Windows services, people would take this approach when the other option would have been to host their service in a virtual machine (AWS EC2 or Azure VM). .NET Core 2.1 has introduced a simpler alternative via the IHost and IHostedService interfaces.

The core idea here is to use the ASP.NET Core framework but without the HTTP engine. The current long term goal is to make this the default (so in future, even web-apps will use the generic host mechanism). So from that perspective, it’s not a bad idea to start using it preemptively. Here’s a really simple fully functional ASP.NET Core generic host service. All it does it launch a timer proc every 5 seconds. Think of it as the equivalent of a scheduled task.

class MyHostedService : IHostedService
{
    public static async Task Main(string[] args)
    {
        await new HostBuilder()
            .ConfigureServices((context, services) =>
            {
                services.AddLogging();
                services.AddHostedService<MyHostedService>();
            })
            .ConfigureLogging((context, logging) =>
            {
                logging.AddConsole();
            })
            .UseConsoleLifetime()
            .Build()
            .RunAsync();
    }

    ILogger<HostedService> _logger;

    public MyHostedService(ILogger<HostedService> logger)
    {
        _logger = logger;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        new Timer(
            state => { _logger.LogInformation("Timer invoked"); },
            this,
            TimeSpan.FromSeconds(0),
            TimeSpan.FromSeconds(5));

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s