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.
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 handlerApplicationStopping
event handlerApplicationStopped
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
.
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.