Created
April 30, 2021 11:33
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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