[英]When does a DbContext instance get disposed in ASP.NET Core 5
I'm using the recommended approach to create DbContext
instance through dependency injection.我正在使用推荐的方法通过依赖注入创建DbContext
实例。
In Startup.cs -在 Startup.cs -
services.AddDbContext<DashboardContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DashboardConnection")));
and in the Controller -并在 Controller -
private readonly DashboardContext db;
public AccountController(DashboardContext context)
{
db = context;
}
What I want to know is when this instance gets disposed.我想知道的是这个实例什么时候被处理掉。
Previously we would always use the using
statement which would dispose on close of braces -以前我们总是使用using
语句来处理大括号的关闭 -
using (DashboardContext db = new DashboardContext())
{
// Query
}
With the AddDbContext
method, a DbContext
will be created with Scoped
lifetime by default;使用AddDbContext
方法,默认情况下会创建一个具有Scoped
生命周期的DbContext
; which means, it's lifetime is scoped within the current request, and it will get disposed as soon as the current request completes.这意味着,它的生命周期在当前请求的范围内,一旦当前请求完成,它就会被释放。
But you can override the default by passing a value for the contextLifetime
parameter, like -但是您可以通过传递contextLifetime
参数的值来覆盖默认值,例如 -
services.AddDbContext<DashboardContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DashboardConnection")),
ServiceLifetime.Transient);
For further detail check - AddDbContext更多细节检查 - AddDbContext
EDIT - (in reply to @Dale's comment):编辑 - (回复@Dale的评论):
Considering the overall architecture of the ASP.NET Core MVC, and how we tend to use the framework, I'd say (personal opinion) that in general for most applications its better to stick to the default Scoped
lifetime.考虑到 ASP.NET 核心 MVC 的整体架构,以及我们倾向于如何使用该框架,我想说(个人意见)通常对于大多数应用程序来说最好坚持默认的Scoped
生命周期。
In the answer, I just wanted to make it clear that the option for manual config is there for you.在答案中,我只是想明确说明手动配置选项适合您。 Of course, there might be use cases or scenarios (depending on how you design your own application) where the manual config has its use.当然,可能存在手动配置有用的用例或场景(取决于您如何设计自己的应用程序)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.