Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Created April 30, 2021 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manoj-choudhari-git/da4e23eb3d0c97bf0ba707f58b8531f1 to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/da4e23eb3d0c97bf0ba707f58b8531f1 to your computer and use it in GitHub Desktop.
Example Hosted Service using IHostApplicationLifetime to customize the post-start logic
// ExampleHostedService
class ExampleHostedService : IHostedService
{
private readonly ILogger _logger;
private readonly IHostApplicationLifetime _appLifetime;
public ExampleHostedService(
ILogger<ExampleHostedService> logger,
IHostApplicationLifetime appLifetime)
{
_logger = logger;
_appLifetime = appLifetime;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_appLifetime.ApplicationStarted.Register(OnStarted);
_appLifetime.ApplicationStopping.Register(OnStopping);
_appLifetime.ApplicationStopped.Register(OnStopped);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
private void OnStarted()
{
_logger.LogInformation("ExampleHostedService: OnStarted has been called.");
// Perform post-startup activities here
}
private void OnStopping()
{
_logger.LogInformation("ExampleHostedService: OnStopping has been called.");
// Perform on-stopping activities here
}
private void OnStopped()
{
_logger.LogInformation("ExampleHostedService: OnStopped has been called.");
// Perform post-stopped activities here
}
}
// Program.cs
class Program
{
static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((_, services) =>
services.AddTransient<ITransientGetCreatedTime, GetCreatedTimeImplementation>()
.AddScoped<IScopedGetCreatedTime, GetCreatedTimeImplementation>()
.AddSingleton<ISingletonGetCreatedTime, GetCreatedTimeImplementation>()
.AddTransient<GetCreatedTimeInvoker>()
.AddHostedService<ExampleHostedService>());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment