Singletons in web- or WCF-services
for a while I wonder if it is a good idea to store some data in a singleton when writing a web开发者_如何学C-(or WCF)service. The goal is to reuse this information in different calls of the service. I wonder what's the lifetime of those singletons, because for example when the application pool is recycled, the singleton is gone. Next Question is the availability of the singleton. Is it really available in all calls, independent of processes or threads started by the IIS?
What do you think?
Thanks, Rocko
The lifetime of a singleton is equal or lower (if it is lazy loaded) to the lifetime of the application. When the application pool recycles, the application stops and the memory that was used to store the singletons is reclaimed by the operating system.
The singleton will be available in all threads of the application but as it is stored in the memory space of the process running this application it won't be available to other processes.
As to answer your question whether it is a good idea to store data using the singleton pattern in WCF this will entirely depend on your scenario and what you want to store and where do you want it to be available. WCF provides many points of extensions that would allow you to avoid static methods.
A disadvantage of singletons is that they are difficult to unit test so I usually try to avoid them if possible.
精彩评论