c# - 将单例模式与 Entity Framework 上下文一起使用 - 底层提供者在打开时失败

标签 c# entity-framework wcf design-patterns

我正在尝试使用 Entity Framework 向我的 DbContext 添加单例模式。我一直为此使用单例模式,之前从未遇到过此错误。 我知道单例是最佳实践 (显然不是)但如果你们有空,能否请您解释一下为什么单例是最佳实践?

问题

除此之外,我收到此错误:

The underlying provider failed on open

让我们看看我的代码

DAO.cs

public class DAO
{
    private static HourRegistrationEntities hourRegInstance;

    public static HourRegistrationEntities HourRegInstance { get { return hourRegInstance = hourRegInstance ?? new HourRegistrationEntities(); } }
}

Service.cs(示例方法)

/// <summary>
/// Return a list of all denied Hour Registration for the Login with the given stringId
/// </summary>
/// <param name="stringId"></param>
/// <returns>A list of HourRegistrationDTO</returns>
public List<HourRegistrationDTO> GetAllDeniedHoursForLogin(string stringId)
{
    var id = Int32.Parse(stringId);
    using (var db = DAO.HourRegInstance)
    {
        var dbHours = db.HourRegistration.Where(x => x.LoginProject.Login.ID == id && x.Denied == true).ToList();
        var returnList = new List<HourRegistrationDTO>();
        foreach (var item in dbHours)
        {
            returnList.Add(new HourRegistrationDTO()
            {
                Id = item.ID,
                Hours = item.Hours,
                Date = item.Date.ToShortDateString(),
                Comment = item.Comment,
                CommentDeny = item.CommentDeny,
                LoginProject = new LoginProjectDTO()
                {
                    Project = new ProjectDTO()
                    {
                        Title = item.LoginProject.Project.Title
                    }
                }
            });
        }
         return returnList;
    }            
}

如前所述,我总是使用单例模式,但从未以前遇到过此错误。是什么原因造成的,为什么?

更新:

我基本上是这样做的(下面的代码),因为这样可以解决问题。现在我更好奇是什么导致了错误。

Service.cs

using (var db = new HourRegistrationEntities())

最佳答案

它不起作用的原因是您的 using 子句在首次使用后处理您的单例实例。在那之后,它变得无用,被处置但仍然不为空。

你坚持说你总是使用单例并且它总是有效的事实并没有任何意义。将单例用于数据上下文被认为是一个非常糟糕的习惯,会导致许多问题,包括内存、并发和事务问题。

我的猜测是,之前您总是在单线程桌面应用程序上工作,其中单例仍然存在风险但不会立即导致问题。然而,在 Web 服务的并发世界中,它根本行不通。

另一方面,每次 wcf 调用创建一个新实例是完全有效的,不同的实例不会干扰,您可以在使用后正确处理它们。

关于c# - 将单例模式与 Entity Framework 上下文一起使用 - 底层提供者在打开时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32268335/

相关文章:

c# - Entity Framework 更新具有一对多关系的两个表

用于 MetaWeblog 的 WCF

WCF REST 与 Windows Phone 通信

c# - 输入不是有效的 Base64 字符串,因为它在 C# 中包含非 base 64 字符?

c# - 静态内存管理

c# - 如何使用 MacinCloud 从 Xamarin Studio 获取 IPA 文件

c# - EF 核心 : The INSERT statement conflicted with the FOREIGN KEY constraint

c# - 如何在 Entity Framework 中设置两个一对多关系?

c# - 为什么将此代码片段从 C# 转换为 C++ 会降低性能?

c# - 如何序列化第 3 方类型以跨 AppDomain 进行通信?