跨 HttpHandler 请求实现 Singleton
我正在尝试创建一个单例服务,用于处理对 HttpHandler 的传入请求。目前,该服务正在根据每个请求进行实例化。我调用保存服务实例的静态类,作为单例实现,如下所示:
public static class ServerApplication {
static Service instance = null;
static readonly object padlock = new object();
/// <summary>
/// Service singleton.
/// </summary>
public static Service Service {
get {
lock (padlock) {
if (instance == null) {
instance = new Service();
}
return instance;
}
}
}
并使用 HttpHandler 中的调用访问它,如下所示:
ServerApplication.Service.Process(request);
我已在 instance = new Service( );
行并且有多个请求 每个请求都会触发断点。
我的目标是一种跨请求存在的服务,因为它加载和缓存来自文件和数据库的大量数据,这些数据可被大多数请求重用。
任何人都可以看到出了什么问题吗?
I am attempting to create a singleton service that is used to process incoming requests to an HttpHandler. At the moment the service is being instantiated on every request. I make a call to the static class that holds an instance of the service, implemented as a singleton as below:
public static class ServerApplication {
static Service instance = null;
static readonly object padlock = new object();
/// <summary>
/// Service singleton.
/// </summary>
public static Service Service {
get {
lock (padlock) {
if (instance == null) {
instance = new Service();
}
return instance;
}
}
}
And access it using a call as below in the HttpHandler:
ServerApplication.Service.Process(request);
I have set a breakpoint on the instance = new Service();
line and with multiple requests the
breakpoint is triggered per request.
My aim is a service that exists across requests as it loads and caches lots of data from files and databases that is reused with most requests.
Can anyone see what is going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有几点:
这应该涵盖并发方面的内容。也有可能(尽管不太可能)您的 AppDomain 在请求之间被卸载(即,您在 Web 目录中写入了一个文件,导致 ASP.NET 认为您的应用程序已过时),这将导致静态数据被重置。
A couple of things:
That should cover you on the concurrency fronts. It's also possible (though less likely) that your AppDomain is being unloaded between requests (ie, you wrote a file inside the web directory causing ASP.NET to think your app is stale), which would cause the statics to be reset.
HTTP 设计用于建立多个并发连接,我不知道您是否想要打破它,除非您在页面加载时建立很少的连接。也就是说,也许您可以将 HttpHandler 保留在 Session 中?
HTTP is designed to make several concurrent connections, I don't know that you'd want to break this, unless you make very few connections on page loads. That said, perhaps you could keep the HttpHandler in the Session?
一般来说,如果你想要一个单例 - 不知道是否有必要,我通常这样实现它: http://www.vikingworks.dk/page/Creating-a-Singleton-Pattern-iC.aspx
Generally speaking, if you want a singleton - cannot see if its necessary i usually implement it this way: http://www.vikingworks.dk/page/Creating-a-Singleton-Pattern-i-C.aspx