So, An object that uses the singleton pattern can only have one instance. How does this work on websites?
Questions:
- Is the singleton object unique to each client/visitor of the website? i.e. Do singleton objects get one instance PER client?
- Objects in web applications only last for a few seconds, so if two clients simotaneously access a website both clients would be trying to create a singleton object. Does this mean one would have an exception thrown that visitors will see? I tried googling, but couldn’t find a direct answer. I’m just looking for a little clarification.
Steve, I’ll try to answer each of your questions:
1) For web development it is very common to have objects scoped to the web request (sometimes this is also referred to as “per request context” or “per http context”), but we typically don’t refer to these as singletons for that exact reason. Most IOC containers in fact have a “per web request” scope built into them out of the box as well as a “singleton”.
2) It is common to sometimes have true singletons for a web application as well (accessed by all requests). As mentioned above this isn’t completely true because it’s going to be scoped to the app pool and will be blown away when/if the app pool is restarted. But this is a singleton for the purposes of the web application. As Jigar mentioned, sometimes “cross-cutting concerns” such as logging etc…are set up this way. These are typically not initialized in each web request but instead in the global.asax or by relying on an IOC container to do this for you. You just have to be sure when performing object creation to use one of the standard locking patterns to prevent two threads/clients/etc… from simultaneously creating the object. Here’s a link from Microsoft but there are other implementations out there as well: http://msdn.microsoft.com/en-us/library/ff650316.aspx If you are using one of the popular IOC containers it will take care of this for you (Structuremap, Windsor, Autofac, Unity, Ninject…and many others).
You’d need to ask your coworkers which approach they are referring to because both are valid in certain situations and very common.