ASP.NET 中的静态方法问题
我对 ASP.NET 中的静态方法有疑问。我创建了下面的单例。在执行过程中,我会多次调用Context.getInstance(),并且需要相同的上下文值。但是,一旦我向服务器发出另一个请求(获取、发布,无论何处),我就需要一个新的上下文,因为我的上下文依赖于 .NET HttpContext。但是,不幸的是,一旦我第一次调用 getInstance,该类将永远不会再次实例化。
我有什么想法如何解决这个问题吗?
public class Context
{
private static Context _context = null;
private Context()
{ ... }
public static Context getInstance()
{
if (Context._context == null)
_context = new Context();
return _context;
}
}
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 instantiated 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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
删除静态变量并将其存储在 HttpContext.Current.Items 中。
Get rid of your static variable and store it in
HttpContext.Current.Items
.如果我理解正确的话,您只需要在单页请求中提供上下文,对吗?
如果是这样,上面的方法肯定行不通——静态将在应用程序域的生命周期内存在。该寿命可能因多种因素而异。
我首先创建一个基本页面类(继承自核心 ASP.NET 页面类)并在其上包含一个 Context 属性。由于该页面仅针对一个请求“存在”,因此这应该适合您。
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.
另一种方法 - 我更喜欢使用我自己的 ThreadStatic 变量(ala HttpContext.Current)而不是使用 HttpContext Items 集合,只是因为我认为(一种意见)它可以使代码更清晰。 YMMV。
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.
如果你的变量是静态的,那么所有用户都将访问同一个变量,并且对该变量的任何更改都会影响所有用户(仅在 Web 应用程序的情况下),逻辑是当你将变量设置为静态时,则在服务器中分配内存位置该位置被分配给所有用户共享该位置,只是因为它是静态的。
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.