将 Dbcontext 配置为瞬态 [英] Configuring Dbcontext as Transient

查看:16
本文介绍了将 Dbcontext 配置为瞬态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ASP.NET Core/EntityFramework Core 中,services.AddDbContext<> 方法会将指定的上下文添加为作用域服务.我的理解是,这是 Microsoft 建议的 dbcontext 生命周期管理.

In ASP.NET Core / EntityFramework Core, the services.AddDbContext<> method will add the specified context as a scoped service. It's my understanding that that is the suggested lifetime management for the dbcontext by Microsoft.

然而,我们的工程师部门对此有很多争论,许多人认为需要尽快处理上下文.那么,将 dbcontext 配置为 Transient 的最佳方法是什么,它仍然保持通常使用的相同 Repository 模式(即,将上下文直接注入到存储库的构造函数中)并支持灵活的单元测试?

However, there is much debate in our engineer department over this and many feel that the context needs to be disposed of ASAP. So, what is the best way to configure the dbcontext as Transient that still maintains the same Repository pattern typically used (i.e. injecting the context directly into the repository's constructor) as well as supporting flexible unit testing?

推荐答案

生命周期是 AddDbContext<>() 上的一个参数.见示例:

The lifetime is a parameter on AddDbContext<>(). See example:

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

这会将其添加到具有瞬态生命周期的服务集合中.

This will add it to the service collection with transient lifetime.

这篇关于将 Dbcontext 配置为瞬态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆