【问题标题】:Singleton Design Pattern in a web environment [duplicate]Web环境中的单例设计模式[重复]
【发布时间】:2015-09-09 19:26:36
【问题描述】:

我在我的 asp.net 网站中使用了用户信息的单例类。

我想知道,如果我把这个网站放到网上,当用户开始登录时,这个类将只存储一个用户的数据。

这是我的课:

public class User
{
    private static User instance;        
    private User(){}

    public static User Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new User();
            }
            return instance;
        }
    }

    public Institute LoggedInstitute { get; set; }
    public List<Institute> Institutes { get; set; }
}

【问题讨论】:

  • 请分享您的代码进行评估,以便我们做出回应
  • public class User { private static User instance; private User(){} public static User Instance { get { if (instance == null) { instance = new User(); } return instance; } } public Institute LoggedInstitute { get; set; } public List&lt;Institute&gt; Institutes { get; set; } }
  • 我试图把自动换行..但是没有用... :(
  • 你应该把你的代码放在问题中。

标签: asp.net design-patterns web-applications


【解决方案1】:

当用户开始登录时,这个类会将数据存储到 只有一个用户。

您的应用程序中只会存在一个 User 实例。

将每个用户信息存储在 Singleton 中对于 Web 应用程序来说是一个非常非常非常糟糕的主意。为什么?

多个用户请求您的 Web 应用程序,他们都将共享同一个 User 实例。我保证这不是你想要的。

理想情况下,在 Web 应用程序中,您希望创建 Principal 对象,并将其存储在 HttpContext 中。

仅供参考:我们在 Web 应用程序中使用 Singleton 来存储信息(大多数情况下不会更改),这些信息在应用程序的开头一直使用到结尾。

【讨论】:

  • 谢谢你!我试试看!
  • this answer关于如何创建Principal对象。
【解决方案2】:

如果您的应用程序用于网络农场场景,您的类只会有多个实例。参考本帖:Are static class instances unique to a request or a server in ASP.NET?

【讨论】:

  • 所以,只是为了确认一下,如果我使用我的凭据登录应用程序,并且在我另一个用户登录应用程序后,它将获取我的用户数据?
  • 我不明白你为什么要使用静态来存储用户?如果您希望此信息在每个会话中都是唯一的 - 您应该将此信息存储在 Session 中。
  • 因为数据卷大小
【解决方案3】:

C#(我相信所有 .NET 语言)中的静态字段,例如用于保存 User 类的单例实例的静态字段,在 AppDomain 中是“唯一的”。

当且仅当您有多个 AppDomain,无论是在同一个进程中、在另一个进程中还是在另一台机器上(例如在网络农场中),正如 William 在他的 answer 中指出的那样,您可以拥有多个实例。

Scope of static variables in ASP.NET sites

In .Net is the 'Staticness' of a public static variable limited to an AppDomain or the whole process?

【讨论】:

    猜你喜欢
    • 2017-08-19
    • 2012-07-06
    • 2018-02-03
    • 2011-06-25
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    相关资源
    最近更新 更多