c# - 具有 Entity Framework dbcontext 的 Singleton 好吗?

标签 c# entity-framework singleton dbcontext

我的问题太简单了,我有一个想法,通过使用一个实例来管理一个DbContext对象,所以这个想法是使用单例设计模式。

根据您的经验,单例是否适合与 Entity Framework dbcontext 一起使用以确保仅使用一个 dbcontext 实例?

最佳答案

Is singleton good to use with entity framework dbcontext to ensure that one dbcontext instance is used?

这不仅是一个坏主意,而且行不通。它不是线程安全的,并发使用时会生成异常。长期存在的 DbContext 往往会在其更改跟踪器中积累大量对象,从而降低性能并浪费资源。

The lifetime of a DbContext begins when the instance is created and ends when the instance is disposed. A DbContext instance is designed to be used for a single unit-of-work. This means that the lifetime of a DbContext instance is usually very short.

DbContext Lifetime, Configuration, and Initialization

关于c# - 具有 Entity Framework dbcontext 的 Singleton 好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65872526/

相关文章:

c# - 动态创建代理类

c# - 如何将 EF 属性转换为 SQL Server 的计算列?

java - 使用双重检查阻塞方法实例化单例

c++ - 以下是C++单例实现吗?

c++ - boost pool_alloc

c# - 为什么我的 .NET 组件上的索引器并不总是可以从 VBScript 访问?

c# - 自定义 JSON.NET 转换器,将字符串转换为类型

c# - DDD、事件存储、UI

c# - 在 Controller 操作中执行 SQL 查询

c# - 如何修复 : The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical?