何时在ASP.NETCore5中处理DbContext实例

c#

我正在使用推荐的方法来创建 DbContext通过依赖注入实例。

在 Startup.cs -

services.AddDbContext<DashboardContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DashboardConnection")));

并在控制器中 -

private readonly DashboardContext db;
public AccountController(DashboardContext context)
{
    db = context;
}

我想知道的是这个实例什么时候被处理掉。

以前我们总是使用在using大括号结束时处理的语句 -

using (DashboardContext db = new DashboardContext())
{
    // Query
}

回答

使用该AddDbContext方法,DbContext将创建一个Scoped默认情况下生命周期的a;这意味着,它的生命周期在当前请求范围内,一旦当前请求完成,它就会被处理掉。

但是您可以通过为contextLifetime参数传递一个值来覆盖默认值,例如 -

services.AddDbContext<DashboardContext>(options => 
    options.UseSqlServer(
        Configuration.GetConnectionString("DashboardConnection")),
        ServiceLifetime.Transient);

进一步的细节检查 - AddDbContext

编辑 - (回复@Dale 的评论):
考虑到 ASP.NET Core MVC 的整体架构,以及我们如何倾向于使用该框架,我会说(个人意见)一般来说,对于大多数应用程序来说,最好坚持到默认Scoped生命周期。
在回答中,我只是想明确说明手动配置选项适合您。当然,可能存在手动配置使用的用例或场景(取决于您如何设计自己的应用程序)。

  • @DaleFraser Let's say a controller has a dependency on IBob and ICathy. Cathy (the ICathy) also has a dependency on IBob. Do you want the controller and Cathy to share the same IBob? If so - IBob should be Scoped. If not - IBob should be Transient. _Disposal wise - Transient and Scoped will act the same, they'll `Dispose` when the web request ends._ I'd argue for _most_ scenarios `Transient` is the safer default.

以上是何时在ASP.NETCore5中处理DbContext实例的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>