Dbcontext注册为“作用域”或“瞬态”对关闭数据库连接有影响吗

sec*_*age 3 c# entity-framework asp.net-core-mvc

我对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
}
Run Code Online (Sandbox Code Playgroud)

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

因此,在请求完成后,_context也会被处理。那么这与范围服务的效果不一样吗?我们打算将其注册为“瞬态”服务,最后它就像“范围”服务一样工作,因此将Dbcontext注册为“范围”或“瞬态”真的不重要吗?

kre*_*dyf 6

如果您不使用任何其他注入的服务(也在使用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
}
Run Code Online (Sandbox Code Playgroud)