Table of Contents

ConsoleHostedService<TStartup> Class

Definition

Namespace
Codebelt.Bootstrapper.Console
Assemblies
Codebelt.Bootstrapper.Console.dll
Source
src/Codebelt.Bootstrapper.Console/ConsoleHostedService.cs

Provides a console application that is managed by its host.

public class ConsoleHostedService<TStartup> : IHostedService where TStartup : ConsoleStartup

Type Parameters

TStartup

The type containing the startup methods for the application.

Inheritance
ConsoleHostedService<TStartup>
Implements

Examples

The following example shows how ConsoleHostedService<TStartup> is registered by UseConsoleStartup<TStartup> on the conventional IHostBuilder, and how the hosted service itself can be resolved from the host's service collection. When the host starts, the service logs a RunAsync started. message through BootstrapperLogMessages, runs the TStartup.RunAsync task, and then calls IHostApplicationLifetime.StopApplication to begin a graceful shutdown.

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Codebelt.Bootstrapper.Console;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace ConsoleHostedServiceDemo;

public class MyStartup : ConsoleStartup
{
    public MyStartup(IConfiguration configuration, IHostEnvironment environment) : base(configuration, environment)
    {
    }

    public override void ConfigureServices(IServiceCollection services)
    {
    }

    public override Task RunAsync(IServiceProvider serviceProvider, CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }
}

public static class Program
{
    public static void Main()
    {
        var host = Host.CreateDefaultBuilder()
            .UseConsoleStartup<MyStartup>()
            .Build();

        var hosted = host.Services.GetServices<IHostedService>();
        var consoleHosted = hosted.OfType<ConsoleHostedService<MyStartup>>().Single();
    }
}

Constructors

Name Description
ConsoleHostedService(IStartupFactory<TStartup>, IHostApplicationLifetime, IServiceProvider, IHostLifetimeEvents)

Initializes a new instance of the ConsoleHostedService<TStartup> class.

Methods

Name Description
StartAsync(CancellationToken)

Triggered when the application host is ready to start the service.

StopAsync(CancellationToken)

Triggered when the application host is performing a graceful shutdown.

See Also