2

我正在用 asp.net core 2.1 编写一个包含托管服务的应用程序。原因是每隔一段时间我需要对数据库进行一些检查。

我遇到了一些问题。我无法在托管服务中注入数据库上下文,因为托管服务是单例服务,而数据库上下文是范围服务。

我试图通过创建一个额外的 Web API 来处理我需要做的事情并让我的托管服务在需要时调用该 API 来解决这个问题。这增加了一个公开 API 的问题,并且必须将绝对 URL 硬编码到我的托管服务类中,因为相对 URL 不起作用。

对我来说,这整件事感觉就像一个黑客。也许有更好的方法来实现我所需要的。因此,我在这里向某人寻求有关我的问题的最佳实践的建议。谢谢!

4

1 回答 1

4

要在 a 中使用作用域对象,IHostedService您必须使用IServiceScopeFactory. 在此范围内,您可以使用范围服务。Consuming a scoped service in a background task的文档对此进行了解释。

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
              ...          
        }
    }
}
于 2018-10-18T02:32:56.730 回答