开发者

Issue with static method in ASP.NET

I have an issue with the static method in ASP.NET. I created the Singleton below. During the execution process I will call Context.getInstance() several times and I need the same context value. But, once I make another request (Get, Post, wherever) to the server I need a new context because my context is dependant from .NET HttpContext. But, unfortunately once I call getInstance for the first time the class never will be i开发者_如何学编程nstantiated again.

Any ideas how I solve this problem?

public class Context
{
   private static Context _context = null;

   private Context()
   { ... }

   public static Context getInstance()
   {
       if (Context._context == null)
           _context = new Context();

       return _context;
   }
}


Get rid of your static variable and store it in HttpContext.Current.Items.

public static Context GetInstance()
{
    if (HttpContext.Current.Items["MyContext"] == null) 
    {
        HttpContext.Current.Items["MyContext"] = new Context();
    }
    return (Context)HttpContext.Current.Items["MyContext"];
}


If I understand you correctly, you need the context only in a single page request, correct? If so, the method above certainly won't work - the static will live for the life of the app domain. This lifetime can vary depending on a number of factors. I would start by creating a base page class (inheriting from the core ASP.NET Page class) and include a Context property on it. Since the page only "lives" for one request, that should work for you.


Another approach - I prefer using my own ThreadStatic variables (ala HttpContext.Current) rather than use the HttpContext Items collections simply because I think (an opinion) that it makes for cleaner code. YMMV.

public class Context
{
    [ThreadStatic()]
    private static Context _Context = null;

    private HttpContext _HttpContext = null;

    public Context()
    {
        _HttpContext = HttpContext.Current;
    }

    public static Context Current
    {
        if(_Context == null || 
           _HttpContext != _HttpContext.Current)
        {
            _Context = new Context();
        }
        return _Context;
    }
}


if your variable is static then all user will access that same variable and any change to that variable will effect all users in case of web-application only, the logic is when your are making a variable static then a memory location is allocated in server when this location is allocated all users share that location only because it is static.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜