ASP.NET Core 2.1 无法从托管服务访问数据库上下文
ASP.NET Core 2.1 Cannot access database context from a hosted service
我正在 asp.net 核心 2.1 中编写一个应用程序,其中包含托管服务。原因是每隔一段时间我需要 运行 对数据库进行一些检查。
我运行遇到了一些问题。我无法在托管服务中注入数据库上下文,因为托管服务是单例服务,而数据库上下文是作用域服务。
我试图通过创建一个额外的网络 API 来处理我需要做的事情并让我的托管服务在需要时调用 API 来解决这个问题。这增加了暴露 API 并且必须将绝对 URL 硬编码到我的托管服务 class 中的问题,因为相对 URL 不起作用。
对我来说,这整件事就像是一个 hack。也许有更好的方法来实现我的需要。因此,我在这里向某人征求有关我的问题的最佳做法的建议。谢谢!
要在 IHostedService
中使用范围对象,您必须使用 IServiceScopeFactory
创建依赖注入范围。在此范围内,您可以使用范围内的服务。
doc在后台任务中使用范围内的服务已经解释过了。
public class TimedHostedService : IHostedService, IDisposable
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger _logger;
private Timer _timer;
public TimedHostedService(ILogger<TimedHostedService> logger, IServiceScopeFactory scopeFactory)
{
_logger = logger;
_scopeFactory = scopeFactory;
}
// Other methods
private void DoWork(object state)
{
_logger.LogInformation("Timed Background Service is working.");
using (var scope = _scopeFactory.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<YourDbContext>();
//Do your stuff with your Dbcontext
...
}
}
}
我正在 asp.net 核心 2.1 中编写一个应用程序,其中包含托管服务。原因是每隔一段时间我需要 运行 对数据库进行一些检查。
我运行遇到了一些问题。我无法在托管服务中注入数据库上下文,因为托管服务是单例服务,而数据库上下文是作用域服务。
我试图通过创建一个额外的网络 API 来处理我需要做的事情并让我的托管服务在需要时调用 API 来解决这个问题。这增加了暴露 API 并且必须将绝对 URL 硬编码到我的托管服务 class 中的问题,因为相对 URL 不起作用。
对我来说,这整件事就像是一个 hack。也许有更好的方法来实现我的需要。因此,我在这里向某人征求有关我的问题的最佳做法的建议。谢谢!
要在 IHostedService
中使用范围对象,您必须使用 IServiceScopeFactory
创建依赖注入范围。在此范围内,您可以使用范围内的服务。
doc在后台任务中使用范围内的服务已经解释过了。
public class TimedHostedService : IHostedService, IDisposable
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger _logger;
private Timer _timer;
public TimedHostedService(ILogger<TimedHostedService> logger, IServiceScopeFactory scopeFactory)
{
_logger = logger;
_scopeFactory = scopeFactory;
}
// Other methods
private void DoWork(object state)
{
_logger.LogInformation("Timed Background Service is working.");
using (var scope = _scopeFactory.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<YourDbContext>();
//Do your stuff with your Dbcontext
...
}
}
}