You are currently viewing Three Important Interfaces Related To .NET Generic Host

Three Important Interfaces Related To .NET Generic Host

This article is an extension to previous article about .NET generic host. There are many framework provided services, which are registered automatically. For full list, see Dependency injection in ASP.NET Core.

For the purpose of understanding the generic host better, let’s have a quick look at three interfaces. These are also registered automatically.

IHostEnvironment

This is a simple interface, registered automatically. This interface provides below information:

For web application, specialized interface IWebHostEnvironment is used. IWebHostEnvironment extends IHostEnvironment. This specialized interface adds another setting for getting information about Web Root path.

As this interface is registered automatically, it can be injected to any class (including Startup). Below example shows how this is being used to identify the current environment.

// IWebHostEnvironment extends IHostEnvironment
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days.
// You may want to change this for production scenarios,
// see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
}
view raw Startup.cs hosted with ❤ by GitHub

IHostLifetime

The IHostLifetime implementation controls when the host starts and when it stops.

It has two methods:

StopAsync(CancellationToken)

Called from StopAsync(CancellationToken) to indicate that the host is stopping and it’s time to shut down.

WaitForStartAsync(CancellationToken)

Called at the start of StartAsync(CancellationToken) which will wait until it’s complete before continuing. This can be used to delay startup until signaled by an external event.

For better understanding this interface, we can check the ConsoleLifetime implementation from the GitHub.

IHostApplicationLifetime

This is very useful to handle post startup and graceful shutdown tasks. It has cancellation tokens for:

  • ApplicationStarted event handler
  • ApplicationStopping event handler
  • ApplicationStopped event handler

Apart from cancellation token, this interface also has StopApplication method. Below is a sample implementation of IHostedService. In this code snippet, we have injected IHostApplicationLifetime.

// 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>());
}
view raw Program.cs hosted with ❤ by GitHub

These three interfaces play vital role in assigning values to important settings, like environment name, content root path or web root path. These interfaces also provide control over activities to be done on startup and also over graceful shutdown of the program.

I hope you find this information useful. Let me know your thoughts.

Leave a Reply