[英]Issue with static method in ASP.NET
I have an issue with the static method in ASP.NET. 我在ASP.NET中的静态方法有问题。 I created the Singleton below. 我在下面创建了Singleton。 During the execution process I will call Context.getInstance() several times and I need the same context value. 在执行过程中,我将多次调用Context.getInstance(),并且我需要相同的上下文值。 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. 但是,一旦我向服务器发出另一个请求(Get,Post,无论在何处),我就需要一个新的上下文,因为我的上下文依赖于.NET HttpContext。 But, unfortunately once I call getInstance for the first time the class never will be instantiated again. 但是,不幸的是,一旦我第一次调用getInstance,就永远不会再次实例化该类。
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
. 摆脱静态变量并将其存储在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. 我将首先创建一个基页类(从核心ASP.NET Page类继承),并在其上包含一个Context属性。 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. 另一种方法-我更喜欢使用自己的ThreadStatic变量(例如HttpContext.Current)而不是使用HttpContext Items集合,这仅仅是因为我认为(这样认为)它可以使代码更简洁。 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;
}
}
如果您的变量是静态的,那么所有用户都将访问同一变量,并且对该变量的任何更改将仅在Web应用程序的情况下影响所有用户,逻辑是当您将变量设为静态时,则在服务器上分配内存位置时分配此位置是所有用户共享该位置的唯一原因,因为它是静态的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.