首页 > 解决方案 > 在 DependencyInjection 之外创建 DBContext

问题描述

我正在创建一个 ASP.NET Core 应用程序。它使用 Entity Framework Core 进行数据库访问。我在 Startup.cs 中使用 services.AddDbContext 并且数据库上下文按预期注入到我的控制器中。

我还有一个使用 IHostedService 作为单例添加的后台任务。我想在我的 IHostedService 实现中有一个我的 DBContext 实例。当我尝试这样做时,我得到一个运行时错误,我的 IHostedService 无法使用范围服务(我的数据库上下文)。

DB Context 类采用 DbContextOptions 选项的参数并将选项传递给基本构造函数 (DbContext)。

我需要在 IHostedService (单例对象)的实现中创建我的数据库上下文的实例,但我似乎无法弄清楚如何从我的 IHostedService 实现中正确创建 DbContextOptions 的新实例。

标签: c#entity-frameworkasp.net-core-2.0

解决方案


Scoped Service要从 a解析 a Singleton Service,您可以从IServiceProvider.

这是演示代码:

    public class DbHostedService : IHostedService
{
    private readonly ILogger _logger;

    public DbHostedService(IServiceProvider services,
        ILogger<DbHostedService> logger)
    {
        Services = services;
        _logger = logger;
    }

    public IServiceProvider Services { get; }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Consume Scoped Service Hosted Service is starting.");

        DoWork();

        return Task.CompletedTask;
    }

    private void DoWork()
    {
        _logger.LogInformation(
            "Consume Scoped Service Hosted Service is working.");

        using (var scope = Services.CreateScope())
        {
            var context =
                scope.ServiceProvider
                    .GetRequiredService<ApplicationDbContext>();

            var user = context.Users.LastOrDefault();

            _logger.LogInformation(user?.UserName);
        }
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Consume Scoped Service Hosted Service is stopping.");

        return Task.CompletedTask;
    }
}

参考:在后台任务中使用作用域服务


推荐阅读