c# - 如何在 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?
如何重新开始?
解决方案
仅为调用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();
}
}
推荐阅读
- javascript - JavaScript $ 符号意外行为
- hibernate - Hibernate - 在异常期间记录 sql 和所有参数
- c# - 部署 .NET Core 站点时,Ajax 调用返回 401
- php - 在 Laravel 中自动验证所有必需的输入
- azure - 发布后 Azure 功能不活动
- .htaccess - 将所有内容重定向到索引(使用 htaccess 并且不弄乱图像)
- python - 更改 Widget 的所有实例的 Qt 样式表
- java - JUnit 4 测试
- php - 如何从下拉菜单和不同页面中的输入一起计算答案?(HTML & PHP)
- azure-cli - 通过 CLI 创建 AKS 失败:协调标准负载均衡器失败