.NET Core BackgroundService 中使用依赖注入
在 .NET Core 中,使用依赖注入 (DI) 非常常见,因此在 BackgroundService 中使用它也很容易。
以下是一些步骤:
- 在 Startup.cs 文件中,将服务注册到容器中:
services.AddScoped<IMyService, MyService>();
- 在 BackgroundService 类的构造函数中注入服务:
public MyBackgroundService(IMyService myService)
{
_myService = myService;
}
- 在 ExecuteAsync 方法中使用服务:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// 使用服务
await _myService.DoSomethingAsync();
await Task.Delay(1000, stoppingToken);
}
}
在这个例子中,我们使用 AddScoped 方法将服务注册到容器中,然后将它注入到 MyBackgroundService 的构造函数中。在 ExecuteAsync 方法中,我们使用服务的方法来完成一些任务。
这是一种非常基本的使用依赖注入的方式,但是可以根据需要进行扩展和改进。
原文地址: https://www.cveoy.top/t/topic/nSWj 著作权归作者所有。请勿转载和采集!