【问题标题】:What is the difference between instantiating DbContext and Getting DbContext service with IServiceScopeFactory in a hosted service在托管服务中实例化 DbContext 和使用 IServiceScopeFactory 获取 DbContext 服务有什么区别
【发布时间】:2022-07-29 17:57:24
【问题描述】:

我想为我的应用程序创建一个后台任务,在该任务中,我需要 DbContext 每 5 秒对数据进行一次操作。我尝试了两种获取 DbContext 的方法,看起来它们都有效,但我现在想要它们之间有什么区别(如果有的话)

这是第一种方法

private readonly IServiceScopeFactory _serviceScopeFactory;

public worker(IServiceScopeFactory serviceScopeFactory)
{
    _serviceScopeFactory = serviceScopeFactory;
}
private void DoWork(object? state)
{
    var scope = _serviceScopeFactory.CreateScope();
    var context = scope.ServiceProvider.GetService<ApplicationDbContext>();
   

}

这是我尝试的第二种方法

private void DoWork(object? state)
{
    using (var db = new ApplicationDbContext(new DbContextOptions<ApplicationDbContext>()))
    {
        //do job
    }
    
}

它们似乎都在工作。当方法调用时,它们不是都被处理和重新创建了吗?有什么区别?你更喜欢哪一个?为什么?

【问题讨论】:

    标签: c# entity-framework dbcontext asp.net-core-hosted-services


    【解决方案1】:

    一般来说,如果您对 dbcontext 使用依赖注入,则它的作用域是整个请求。这意味着在不同的类或方法中使用 dbcontext 将使用相同的事务,例如,您可以在所有更改之后使用.SaveChanges() 提交。依赖注入方法也适用于进行抽象。如果您为您的 dbcontext 创建接口,那么您可以进行两种实现 - 一种是您现有的 dbcontext,另一种例如不使用真实数据库,而是使用内存中的一些数据进行开发。

    如果您使用using 方法,则事务位于 using 括号内,并且无法从多个位置访问,而只能在实例化的位置访问,并且您还与框架紧密耦合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-04
      • 2020-01-21
      • 2011-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多