a request level singleton object in asp.net

柔情痞子 提交于 2019-12-11 12:49:25

问题


I trying to write a kind of pseudo singleton implementation. I want it to work similar to how HttpContext does work, where I can get an instance to the context doing something as simple as:

var ctx = HttpContext.Current;

So my implementation goes something like this:

public class AppUser
{
    public string Username { get; set; }
    public string[] Roles { get; set; }

    public AppUser()
    {
        var appuser = HttpContext.Session["AppUser"] as AppUser;
        if(appuser == null)
            throw new Exception("User session has expired");
        Username = appuser.Username;
        Roles = appuser.Roles;
    }
}


public class WebAppContext
{
    const string ContextKey = "WebAppContext";

    WebAppContext() { } //empty constructor
    public static WebAppContext Current 
    {
        get
        {
            var ctx = HttpContext.Current.Items[ContextKey] as WebAppContext;
            if(ctx == null)
            {
                try
                {
                    ctx = new WebAppContext() { User = new AppUser() };
                }
                catch
                {
                    //Redirect for login
                }
                HttpContext.Current.Items.Add(ContextKey, ctx);                     
            }       
            return ctx;     
        }
    }

    public AppUser User { get; set; }
}

And I try to consume this object as follows:

var appuser = WebAppContext.Current.User;

Now does the above line guarantee I get the user associated with the correct request context; not some other user which is associated with another concurrent http request being processed?


回答1:


Apart from the fact that I can't understand why would you need to barely copy the user information from the Session container to the Items container, the answer to your question should be - yes, if the Session data is correct then the same data will be available from your static property.

I wrote a blog entry on that once

http://netpl.blogspot.com/2010/12/container-based-pseudosingletons-in.html



来源:https://stackoverflow.com/questions/18502493/a-request-level-singleton-object-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!