1
votes

My general use case is that : For my web application (in .net core), I want to create a service. Microsoft since .net core 2.1 purpose to use "Generic host" to create easily a service. But I would like to start and stop my service from my web application that's why I was looking for a solution. In Microsoft documentation I found a way call "External control" https://docs.microsoft.com/fr-fr/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-2.2#external-control

This is the code i'm talking about :

public class Program { 
private IHost _host;

public Program()
{
    _host = new HostBuilder()
        .Build();
}

public async Task StartAsync()
{
    _host.StartAsync();
}

public async Task StopAsync()
{
    using (_host)
    {
        await _host.StopAsync(TimeSpan.FromSeconds(5));
    }
}
}

It seems that we can call generic host from an external application but there is not enough explanation in Microsoft documentation that is why I was looking for help and explanation how to use it or if you have any solution to control a generic host from a .net core web application ? Thx for your help

1

1 Answers

1
votes

You are misreading the word "External". The documentation states:

External control of the host can be achieved using methods that can be called externally:

and then show the following example:

public class Program
{
    private IHost _host;

    public Program()
    {
        _host = new HostBuilder()
            .Build();
    }

    public async Task StartAsync()
    {
        _host.StartAsync();
    }

    public async Task StopAsync()
    {
        using (_host)
        {
            await _host.StopAsync(TimeSpan.FromSeconds(5));
        }
    }
}

External in this context is a piece of code other than the host itself. It should be code in the same process, so like another class or another assembly that is loaded.

External in this context does not mean from another process, that includes a web api or web site.

It seems that we can call generic host from an external application

So this won't work, assuming you are thinking about developing a console app that will build a host and control it from your web app.