-
Virtual Singleton
-
Someone asked me about the ObjectRegistry I was making. The more general pattern which applies here is "Virtual Singleton". A rather crude implementation can be found here.
I rather think of it as a "real singleton" which uses a "key" provider and a "data" provider to simulate a singleton per user (or something else for that matter). The "key" provider provides the key of the data you're trying to retrieve. Using HttpContext.Current.Session is a perfect example of a key provider. You define a fixed session-variable name you will use to store the key, you store the key in the current session, and further down your logic you call the real singleton which will use HttpContext.Current.Session and the session variable that was agreed upon to retrieve the key. Ofcourse, using HttpContext.Current.Session defeats the purpose because I could have just as easily stored my data in the session variable instead of the key. The bigger value lies in the encapsulation I create by putting a façade (namely the real singleton) in front. That way I can swap my key provider, without affecting any depending logic. Also, relying on HttpContext when you have domain logic that might be used both inside and outside an asp.net web environment is not the best of decisions. In that case, it's better to use CallContext as a key provider. The "data" provider can be a hashtable containing the key and corresponding object/value/data. What is managed by the real singleton is up to you (e.g. creating and storing keys using the key provider).