views:

138

answers:

2

Hi

I found something funny, I notice it by luck while I was debugging other thing. I was applying MVP pattern and I made a singleton controller to be shared among all presentations.

Suddenly I figured out that some event is called once at first postback, twice if there is two postback, 100 times if there is 100 postbacks.

because Singleton is based on a static variable which hold the instance, and the static variable live across postbacks, and I wired the event assuming that it will be wired once, and rewired for each postback.

I think we should think twice before applying a singleton in a web application, or I miss something??

thanks

+5  A: 

You should think twice any time you are using static objects in a multi-threaded application (not only the singleton pattern) because of the shared state. Proper locking mechanisms should be applied in order to synchronize the access to the shared state. Failing to do so some very difficult to find bugs could appear.

Darin Dimitrov
+3  A: 

I would think twice about using a Singleton anywhere.

Many consider Singleton an anti-pattern.

Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application.

There are lots of references on Wikipedia that discuss this.

It is very rare to need a singleton and personally I hold them in the same light as global variables.

kervin