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

查看:305
本文介绍了将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的最佳方法是什么,它仍然保持通常使用的相同存储库模式(即,将上下文直接注入到存储库的构造函数中)以及支持灵活的单元测试?

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天全站免登陆