Generic Host
Host definition
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-6.0
A host is an object that encapsulates an app’s resources.
.Net provide an object named Host to isolate control logic and business logic of services.
- Host controlled by .Net runtime, Control logic
- Lifecycle: Timing switch from one stage to another stage.
- HostService controlled by user, Business logic
- Lifecycle events: Register business logics as events, decide detailed actions to take in each stage.
Dependency injection
DI: Dependency injection
IoC: Inversion of Control
To isolate .Net and user logic, implementation of Host and HostService should be not aware of each other.
We can easily do that by introducing Interfaces as contract btw .Net and users. This design pattern is called Dependency Injection.
public Interface
public class MyService : IHostedService
{
private readonly IHostApplicationLifetime _hostApplicationLifetime;
public HostApplicationLifetimeEventsHostedService(
IHostApplicationLifetime hostApplicationLifetime)
=> _hostApplicationLifetime = hostApplicationLifetime;
public Task StartAsync(CancellationToken cancellationToken)
{
_hostApplicationLifetime.ApplicationStarted.Register(OnStarted);
_hostApplicationLifetime.ApplicationStopping.Register(OnStopping);
_hostApplicationLifetime.ApplicationStopped.Register(OnStopped);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
// ...
}
private void OnStarted()
{
// ...
}
private void OnStopping()
{
// ...
}
private void OnStopped()
{
// ...
}
}