Skip to content

.Net: Generic Host and Dependency Injection

Posted on:August 19, 2023 at 10:19 PM

Generic Host

Host definition

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-6.0

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.

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()
    {
        // ...
    }
}