Web 环境中的单例设计模式

Singleton Design Pattern in a web environment

我在我的 asp.net 网站中使用一个单例 class 来获取用户信息。

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

这是我的 class:

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; }
}

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

when the users start to login, this this class will store the data to only one user.

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

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

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

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

仅供参考: 我们在 Web 应用程序中使用 Singleton 来存储信息(大多数情况下从不更改),这些信息在应用程序开始到结束时使用。

C# 中的静态字段(我相信所有 .NET 语言),例如用于保存 User class 的单例实例的字段,在 "unique" 中一个 AppDomain.

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

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?