Search code examples
c#asp.net-corebackground-serviceasp.net-core-5.0

How to restart manually a BackgroundService in ASP.net core


I create the BackgroundService:

public class CustomService : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken cancellationToken)
    {
        //...
    }
}

and I added to the project:

public class Startup
{
    //...

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHostedService<CustomService>();

        //...
    }

    //...
}

How can I find the CustomService from another class?
How to start it again?


Solution

  • Create an interface just for the call to StartAsync:

    public interface ICustomServiceStarter
    {
        Task StartAsync(CancellationToken token = default);
    }
    
    public class CustomService : BackgroundService, ICustomServiceStarter
    {
        //...
        Task ICustomServiceStarter.StartAsync(CancellationToken token = default) => base.StartAsync(token);
        //...
    }
    

    Register the interface as a singleton:

    public class Startup
    {
        //...
        public void ConfigureServices(IServiceCollection services)
        {
            //...
            services.AddSingleton<ICustomServiceStarter, CustomService>();
        }
        //...
    }
    

    and inject ICustomServiceStarter when needed:

    public class MyServiceControllerr : Controller
    {
        ICustomServiceStarter _starter;
    
        public MyServiceController(ICustomServiceStarter starter)
        {
            _starter = starter;
        }
    
        [HttpPost]
        public async Task<IActionResult> Start()
        {
            await _starter.StartAsync();
    
            return Ok();
        }
    }