@Ice^^Heat said:
Lately, I have been throwing Singletons around like there is no tomorrow (hey why use all that memory?? Just make a singleton!). But I've come to see the downside of it. 2 Users could be using the same object. For some situations thats OK, but most of the times it is not.
When you store data in a static variable, the data is available to all users on the entire AppDomain. If you need a single instance of some object per user, put it in the Session instead.
If you like the convenience of using a singleton without actually making a piece of data globally accessible to all users, you can write something like this:
public class MyClass
{
private MyClass() { }
public MyClass Instance
{
get
{
string name = "MyClassInstance";
if (HttpContext.Current.Session[name] == null)
HttpContext.Current.Session[name] = new MyClass();
return (MyClass)HttpContext.Current.Session[name];
}
}
}
MyClass.Instance reads from the session now, so won't be forced to share the same class instance across the entire application context.
Now, I've had the idea of building a little chatroom app, just for fun, nothing serious. I was thinking of a singleton that could hold all the Chatroom objects in a Hashtable or something. Users can then select a chatroom, and get the object reference of the chatroom from the singleton. If 2 users join the same room, they would get the same chatroom reference, thus they would share the data of the chatroom (e.g Messages).It would mean that the IIS application pool has to be configured so that it would not recycle.
In a real situation ofcourse, checks have to be builtin so that the memory won't get out of proportion.
Plz, WTF-rate my idea. How would YOU do it?
Realistically, you should probably not try to reinvent the wheel.
But since its just for fun, your suggestion isn't too terrible, although keeping your implementation thread-safe and low-memory can be a challenge. If you can keep your object model coherent, I'd say go ahead and try to write a little chat system like this.