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

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

问题描述

问题



我应如何(使用标准依赖项注入)将 DbContext 实例注入 IHostedService



我尝试了什么



我目前有我的 IHostedService 类采用 MainContext (源自 DbContext



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


无法使用单例 Microsoft.Extensions.Hosting.IHostedService中的作用域服务 Microsoft.EntityFrameworkCore.DbContextOptions。


所以我试图通过指定以下内容来使 DbContextOptions 瞬变:

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

在我的 Startup 类中。



但根据这解决了Github问题传递的 DbContextOptions 应该具有在 AddDbContext 调用中指定的生存期。 / p>

我无法使数据库上下文成为单例,否则对其的并发调用将产生并发异常(由于不能保证数据库上下文是线程安全的)

解决方案

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



为此,请注入 IServiceScopeFactory 并在需要时使用它来创建作用域。然后从该作用域中解析您需要的任何依赖项。如果您想将逻辑移出托管服务并仅使用托管服务来触发某些工作(例如,定期触发任务-这将定期创建范围,在其中创建任务服务),这还允许您将自定义服务注册为范围内的依赖项。

 公共类MyHostedService:IHostedService 
{
private IServiceScopeFactory只读

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

public void DoWork()
{
使用(var scope = scopeFactory.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService< MyDbContext>();

}
}

}


Question

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

What have I tried

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

When I run the application I get:

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

So I tried to make the DbContextOptions transient by specifying:

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

in my Startup class.

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).

解决方案

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).

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天全站免登陆