我应该如何将 DbContext 实例注入 IHostedService? [英] How should I inject a DbContext instance into an IHostedService?

查看:21
本文介绍了我应该如何将 DbContext 实例注入 IHostedService?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该如何(使用标准依赖注入)将 DbContext 实例注入到 IHostedService 中?

How should I inject (using the standard dependency injection) a DbContext instance into a IHostedService?

我目前让我的 IHostedService 类在构造函数中使用 MainContext(派生自 DbContext)实例.

I currently have my IHostedService class take a MainContext (deriving from DbContext) instance in the constructor.

当我运行应用程序时,我得到:

When I run the application I get:

无法使用来自单例Microsoft.Extensions.Hosting.IHostedService"的范围服务Microsoft.EntityFrameworkCore.DbContextOptions".

Cannot consume scoped service 'Microsoft.EntityFrameworkCore.DbContextOptions' from singleton 'Microsoft.Extensions.Hosting.IHostedService'.

所以我试图通过指定使 DbContextOptions 成为瞬态:

So I tried to make the DbContextOptions transient by specifying:

services.AddDbContext<MainContext>(options => 
                options.UseSqlite("Data Source=development.db"), ServiceLifetime.Transient);

在我的 Startup 类中.

但错误仍然相同,即使根据这个解决的 Github 问题传递的 DbContextOptions 应该具有在 AddDbContext 调用中指定的相同生命周期.

But the error remains the same, even though, according to this solved Github issue the DbContextOptions passed should have the same lifetime specified in the AddDbContext call.

我不能将数据库上下文设为单例,否则对它的并发调用会产生并发异常(因为不能保证数据库上下文是线程安全的).

I can't make the database context a singleton otherwise concurrent calls to it would yield concurrency exceptions (due to the fact that the database context is not guaranteed to be thread safe).

推荐答案

在托管服务内部使用服务的一个好方法是在需要时创建范围.这允许将服务/数据库上下文等与它们设置的生命周期配置一起使用.理论上,不创建范围可能会导致创建单例 DbContext 和不正确的上下文重用(EF Core 2.0 与 DbContext 池).

A good way to use services inside of hosted services is to create a scope when needed. This allows to use services / db contexts etc. with the lifetime configuration they are set up with. Not creating a scope could in theory lead to creating singleton DbContexts and improper context reusing (EF Core 2.0 with DbContext pools).

为此,注入 IServiceScopeFactory 并在需要时使用它来创建作用域.然后从此范围解决您需要的任何依赖项.如果您想将逻辑移出托管服务并使用托管服务仅触发某些工作(例如定期触发任务 - 这将定期创建范围,在这个范围也注入了一个数据库上下文).

To do this, inject an IServiceScopeFactory and use it to create a scope when needed. Then resolve any dependencies you need from this scope. This also allows you to register custom services as scoped dependencies should you want to move logic out of the hosted service and use the hosted service only to trigger some work (e.g. regularly trigger a task - this would regularly create scopes, create the task service in this scope which also gets a db context injected).

public class MyHostedService : IHostedService
{
    private readonly IServiceScopeFactory scopeFactory;

    public MyHostedService(IServiceScopeFactory scopeFactory)
    {
        this.scopeFactory = scopeFactory;
    }

    public void DoWork()
    {
        using (var scope = scopeFactory.CreateScope())
        {
            var dbContext = scope.ServiceProvider.GetRequiredService<MyDbContext>();
            …
        }
    }
    …
}

这篇关于我应该如何将 DbContext 实例注入 IHostedService?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆