这样使用传统的思路吧数据保存在内存里就会失败(惨痛的教训,调试了半天终于发现)。
如果使用了传统的Singleton模式,那么本质上singleton就不存在了,仍然是每次新建。
传统Singleton:
public class ClassicSingleton
{
private static ClassicSingleton instance;
public static ClassicSingleton Instance
{
get
{
lock (typeof(ClassicSingleton))
{
if (instance == null)
instance = new ClassicSingleton();
return instance;
}
}
}
}
{
private static ClassicSingleton instance;
public static ClassicSingleton Instance
{
get
{
lock (typeof(ClassicSingleton))
{
if (instance == null)
instance = new ClassicSingleton();
return instance;
}
}
}
}
为了解决上面的问题,我把数据保存在Application里面,成为针对Asp.net的singleton:
public class AspNetSingleton
{
private const string cacheid = ".aspnetsingleton";
private static AspNetSingleton instance;
public static AspNetSingleton Instance
{
get
{
lock (typeof(AspNetSingleton))
{
AspNetSingleton cache = HttpContext.Current.Application[cacheid] as AspNetSingleton;
if (cache == null)
{
cache = new AspNetSingleton();
HttpContext.Current.Application[cacheid] = cache;
}
return cache;
}
}
}
}
{
private const string cacheid = ".aspnetsingleton";
private static AspNetSingleton instance;
public static AspNetSingleton Instance
{
get
{
lock (typeof(AspNetSingleton))
{
AspNetSingleton cache = HttpContext.Current.Application[cacheid] as AspNetSingleton;
if (cache == null)
{
cache = new AspNetSingleton();
HttpContext.Current.Application[cacheid] = cache;
}
return cache;
}
}
}
}