ASP .NET Singleton

2019-01-11 02:47发布

Just want to make sure I am not assuming something foolish here, when implementing the singleton pattern in an ASP .Net web application the static variable scope is only for the current user session, right? If a second user is accessing the site it is a different memory scope...?

6条回答
Juvenile、少年°
2楼-- · 2019-01-11 03:14

The static variable scope is for the entire app domain, which means other sessions also have access to it. Only if you have a farm with different servers you would have more than one instance of the variable.

查看更多
Luminary・发光体
3楼-- · 2019-01-11 03:21

If you need it to be user or session based then check out the following link. Otherwise, as Otavio said, the singleton is available to the entire domain.

http://samcogan.com/singleton-per-asp-net-session/

查看更多
等我变得足够好
4楼-- · 2019-01-11 03:22

Static members have a scope of the current worker process only, so it has nothing to do with users, because other requests aren't necessarily handled by the same worker process.

  • In order to share data with a specific user and across requests, use HttpContext.Current.Session.
  • In order to share data within a specific request, use HttpContext.Current.Items.
  • In order to share data across the entire application, either write a mechanism for that, or configure IIS to work with a single process and write a singleton / use Application.

By the way, the default number of worker processes is 1, so this is why the web is full of people thinking that static members have a scope of the entire application.

查看更多
做个烂人
5楼-- · 2019-01-11 03:22

As others have mentioned, a static variable is global to the entire application, not single requests.

To make a singleton global to only individual requests, you can use the HttpContext.Current.Items dictionary.

public class Singleton
{
    private Singleton() { }

    public static Singleton Instance 
    {   
        get
        {
            if (HttpContext.Current.Items["yourKey"] == null)
                HttpContext.Current.Items["yourKey"] = new Singleton();
            return (Singleton)HttpContext.Current.Items["yourKey"];
        }
    }
}
查看更多
仙女界的扛把子
6楼-- · 2019-01-11 03:28

Session for entire application per user. ViewState for single asp page.

查看更多
一纸荒年 Trace。
7楼-- · 2019-01-11 03:29

The singleton is used for the entire Application Domain, if you want to store user session-related data, use HttpContext Session which is designed for that purpose. Of course, you probably have to redesign your class structure to be able to come up with a key-value-pair way of dealing with the data you're trying to work with.

查看更多
登录 后发表回答