首页 > 解决方案 > 如何在 ASP.net 核心中手动重新启动 BackgroundService

问题描述

我创建了BackgroundService:

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

我添加到项目中:

public class Startup
{
    //...

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

        //...
    }

    //...
}

如何从另一个类中找到 CustomService?
如何重新开始?

标签: c#asp.net-corebackground-serviceasp.net-core-5.0

解决方案


仅为调用StartAsync创建一个接口:

public interface ICustomServiceStarter
{
    Task StartAsync(CancellationToken token = default);
}

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

将接口注册为单例:

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

并在需要时注入ICustomServiceStarter

public class MyServiceControllerr : Controller
{
    ICustomServiceStarter _starter;

    public MyServiceController(ICustomServiceStarter starter)
    {
        _starter = starter;
    }

    [HttpPost]
    public async Task<IActionResult> Start()
    {
        await _starter.StartAsync();

        return Ok();
    }
}

推荐阅读