c# - 注册为“作用域”或“瞬态”的 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 注册为“作用域”或“瞬态”,似乎真的无关紧要。
解决方案
如果您不使用任何其他注入服务(也使用您的 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
}
推荐阅读
- mysql - 如何从另一个表的另一列中插入数据?
- utf-8 - 如何使用热字符串显示重音字符?
- swift - 创建没有后退按钮 SwiftUI 的 NavigationLink
- javascript - 角路由失败 - 模态弹出
- php - 通过 PHP 批量调整图像大小的问题
- azure - Terraform - 创建 Azure 事件网格订阅 - 可以吗?
- c++ - 编译器在尝试使用继承定义类时出错
- laravel - 如何在 Redis 队列中调度延迟(待处理)作业?
- javascript - Azure DevOps 在部署之前更新代码内的变量
- python - Pygame中如何正确继承Surface类