Should I use a singleton?

做~自己de王妃 提交于 2019-12-08 05:25:30

There's no need for a singleton with all of the associated drawbacks (customary anti-singleton link ).

I like the suggestion to store it in HttpContext.Cache. Some similar alternatives:

  • Store it in HttpApplication.Application

  • Add a property to your application class to store it, then in the relevant HttpModule, store a class-level reference to your application.

I would consider storing the rules in the HttpContext.Cache which is available to all sessions. You could rebuild the cache anytime it was unloaded (due to lack of usage).

Your solution sounds good to me. Particularly if the consuming code isn't modifying data then using a singleton or static class sounds like it shouldn't be a problem. I'm not sure if labeling it as a "singleton" is necessary although I suppose that's how it's behaving.

You could use either a static class that is inherently "cached" because it's in the ASPNET worker process memory, or you could explicitly cache it into the web cache. If you do the latter, you could benefit by adding a file dependency to the cache entry so any file changes would force a reload from cache.

I would not use a singleton since that makes an application harder to test. Most IoC containers can help you replace this pattern with a "single(ton)" instance that is shared between all classes that would use the singleton.

It's so easy to get an IoC container to provide a singleton for you that I think it would be very hard to justify using the traditional Singleton pattern any more.

John K

Singletons can be justified whenever you might need more than one instance of an object. The term "singleton" is slightly misleading because often the same software design pattern is used to control multiple instances of a class.

You can use a static class, or hang a singleton instance on a static reference, or store it in one of the asp.net web collections. Singletons can participate in inheritance in the future etc. etc...As for static class vs Singleton pattern, I'm staying out of that argument because it has been thoroughly addressed online, even on StackOverflow

Just quickly I would say No, just try to bind it to it's 'scope'. If it is application-wide then try to tie it to the application. If it is session-bound put it in the session etc. This helps you if you for instance want to run 2 apps in the same container. I have no experience with ASP.NET, but there seems to be a 'HttpApplicationState'. Could you use that?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!