首页 > 解决方案 > 注册为“作用域”或“瞬态”的 Dbcontext 是否影响关闭数据库连接

问题描述

我对 ASP.NET MVC 中的 DI 有一个基本的了解,但是有一个问题很困扰我。将 Dbcontext 注册为“作用域”或“瞬态”有什么区别吗?下面是一个典型的 mvc 应用程序的一些代码:

public class EmployeeController : Controller
{
    private EmployeeContext _context;

    public EmployeeController(EmployeeContext context)
    {
        _context = context;
    }

    public ActionResult Index()
    {
        return View(context.Employees.ToList());
    }
    
    ...//other action methods that access context's DbSet
}

假设我们注册EmployeeContext为临时服务。在我们运行应用程序之后,应用程序正在侦听任何传入的请求。假设发生了对默认 /Home/Index 的 http 请求,因此EmployeeController 需要创建一个新的实例。DI 将EmployeeContext首先向控制器的构造函数提供一个实例。_context也可用于所有其他操作方法,并且没有任何其他地方需要创建新EmployeeContext服务。

所以请求完成后,_context也会被处理掉。与作用域服务的效果不一样吗?我们打算将其注册为“瞬态”服务,最终它就像“范围”服务一样工作。如果我们将 Dbcontext 注册为“作用域”或“瞬态”,似乎真的无关紧要。

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

解决方案


如果您不使用任何其他注入服务(也使用您的 DBContext),则作用域和瞬态之间没有区别。

但是,如果您使用其他注入服务,在 DBContext 上具有“瞬态”,则每个服务都会获得自己的实例。为了避免这种情况,您应该始终在 DBContext 上使用“作用域”。

在您使用以下代码的示例中,使用“瞬态” EmployeeContext 每个请求将有两个实例:

public class MyService : IMyService 
{
 public MyService(EmployeeContext context)
 {
  // ...
 }
}

public class EmployeeController : Controller
{
    private EmployeeContext _context;
    private _myService;

    public EmployeeController(EmployeeContext context, IMyService myService)
    {
        _context = context;
        _myService = myService;
    }

    public ActionResult Index()
    {
        return View(context.Employees.ToList());
    }

    ...//other action methods that access context's DbSet
}

推荐阅读