Singleton object in IIS Web Garden

Anwar Chandra picture Anwar Chandra · May 23, 2010 · Viewed 7.6k times · Source

I have a lot of Singleton implementation in asp.net application and want to move my application to IIS Web Garden environment for some performance reasons.

CMIIW, moving to IIS Web Garden with n worker process, there will be one singleton object created in each worker process, which make it not a single object anymore because n > 1.

can I make all those singleton objects, singleton again in IIS Web Garden?

Answer

kervin picture kervin · Jun 4, 2010

I don't believe you can ( unless you can get those IIS workers to use objects in shared memory somehow ).

This is a scope issue. Your singleton instance uses process space as its scope. And like you've said, your implementation now spans multiple processes. By definition, on most operating systems, singletons will be tied to a certain process-space, since it's tied to a single class instance or object.

Do you really need a singleton? That's a very important question to ask before using that pattern. As Wikipedia says, some consider it an anti-pattern ( or code smell, etc. ).

Examples of alternate designs that may work include...

  1. You can have multiple objects synchronize against a central store or with each other.
  2. Use object serialization if applicable.
  3. Use a Windows Service and some form of IPC, eg. System.Runtime.Remoting.Channels.Ipc

I like option 3 for large websites. A companion Windows Service is very helpful in general for large websites. Lots of things like sending mail, batch jobs, etc. should already be decoupled from the frontend processing worker process. You can push the singleton server object into that process and use client objects in your IIS worker processes.

If your singleton class works with multiple objects that share state or just share initial state, then options 1 and 2 should work respectively.

Edit

From your comments it sounds like the first option in the form of a Distributed Cache should work for you.

There are lots of distributed cache implementations out there.

  1. Microsoft AppFabric ( formerly called Velocity ) is their very recent move into this space.
  2. Memcached ASP.Net Provider
  3. NCache ( MSDN Article ) - Custom ASP.Net Cache provider of OutProc support. There should be other custom Cache providers out there.
  4. Roll out your own distributed cache using Windows Services and IPC ( option 3 )

PS. Since you're specifically looking into chat. I'd definitely recommend researching Comet ( Comet implementation for ASP.NET?, and WebSync, etc )