473,581 Members | 3,234 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Singleton pattern for the web

I want to get some feedback so don't hold back.

I have a webservice that is responsible for Formatting a ton of information
that is then queried by other applications (agents) that utilize it (the
info).
All this "formatting " and logic I am talking about needs to be done in a
centralized place and accessed by the agents. That is why we chose to go
with a web service.

Now...all this formatting needs to be done and held in memory so the agents
don't have to wait for it.
So we decided to implement a sort of singleton pattern...what do you guys
think?
Here is some sample code:

public class TheManager
{
private static object lockObject = new Object();
private const string CACHE_MANAGER = "Cache:Manager" ;
private List<InfoPacket > _preparedPacket s;

private TheManager() { initFunction(); }

public static InfoPacket GetInfoPacket() {
getManager().ge tInfoPacket(); }

public InfoPacket getInfoPacket() { ......some code ..... return
this._preparedP ackets[0] }

private static TheManager getManager()
{
object o =
System.Web.Http Context.Current .Application.Ge t(CACHE_MANAGER );
TheManager = oManager;
if(o == null)
{
lock(lockObject )
{
o =
System.Web.Http Context.Current .Application.Ge t(CACHE_MANAGER );
if (o == null)
{oManager = new TheManager();
System.Web.Http Context.Current .Application.Ad d(CACHE_MANAGER ,oManager);}
else oManager = (TheManager)o;
}
}
else oManager = (TheManager)o;

return oManager;

}

}

So now in our web service (*.asmx) we can call TheManager.GetI nfoPacket()
and a prepared packet is returned. Again, this is just a snippet of the
code..so we have functions and threads that are preparing the packet. We
are very consious of threading (utilizing lock() where needed). It has
performed VERY well and everything seems to be going as planned.

What do you guys think of a Singleton-esk pattern like the one above?
Jan 23 '06 #1
7 5698
I didn't mean to type "TheManager = oManager";
I meant "TheManager oManager;" Just declaring the object..
Jan 23 '06 #2
INeedADip wrote:
I want to get some feedback so don't hold back.
<snip>
What do you guys think of a Singleton-esk pattern like the one above?


I think that double-checked locking is a bad idea in general. Unless
you know the exact characteristics of the cache - and in particular,
whether or not it places any memory barriers around access - the code
you provided *may* not be thread-safe.

See http://www.pobox.com/~skeet/csharp/singleton.html for more
information about this.

I'd just always lock before getting it out of the cache. I don't
believe you'd even be able to measure the difference in performance,
and it would be safer.

Jon

Jan 23 '06 #3
Any ideas on how to write trace information from a singleton to trace.axd
file? I have a singleton that is instantiated in the application start event
that I cannot for the live of me figure out how to send trace output to the
web trace file.

Thanks and cheers!

"Jon Skeet [C# MVP]" wrote:
INeedADip wrote:
I want to get some feedback so don't hold back.


<snip>
What do you guys think of a Singleton-esk pattern like the one above?


I think that double-checked locking is a bad idea in general. Unless
you know the exact characteristics of the cache - and in particular,
whether or not it places any memory barriers around access - the code
you provided *may* not be thread-safe.

See http://www.pobox.com/~skeet/csharp/singleton.html for more
information about this.

I'd just always lock before getting it out of the cache. I don't
believe you'd even be able to measure the difference in performance,
and it would be safer.

Jon

Jan 24 '06 #4
If you use the HttpContext.Cur rent property, this gives you access to the
current HttpContext, which gives you access to the Trace class:

HttpContext ctx = HttpContext.Cur rent ;
ctx.Trace.Write ("Yo, It's me!");

Peter

--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"asapjim" wrote:
Any ideas on how to write trace information from a singleton to trace.axd
file? I have a singleton that is instantiated in the application start event
that I cannot for the live of me figure out how to send trace output to the
web trace file.

Thanks and cheers!

"Jon Skeet [C# MVP]" wrote:
INeedADip wrote:
I want to get some feedback so don't hold back.


<snip>
What do you guys think of a Singleton-esk pattern like the one above?


I think that double-checked locking is a bad idea in general. Unless
you know the exact characteristics of the cache - and in particular,
whether or not it places any memory barriers around access - the code
you provided *may* not be thread-safe.

See http://www.pobox.com/~skeet/csharp/singleton.html for more
information about this.

I'd just always lock before getting it out of the cache. I don't
believe you'd even be able to measure the difference in performance,
and it would be safer.

Jon

Jan 24 '06 #5
INeedADip,

You did ask for honesty, so here you go =)

I do think your public and private naming conventions need some work.
Having a class called "TheManager " is superfluous. You can drop the "The".

Also, while your private implementation details are private, I don't
like the casing or use of the getManager and getInfoPacket methods. They
should be properties. The only reason they should be methods is if they are
doing significant work justifies a method call (prefixed by "Get")
indicating that it is a significant operation. If they truly should be
methods, then the method names should be capitalized.

But that's just my personal view. I do understand that there are naming
conventions for private code for companies, and that stuff does not change
easily or overnight. However, I do think that private implementation
guidelines should mimic the public naming conventions (which you are
adhering to pretty well it would seem).

As for the real meat and potatoes, why are you storing the singleton in
the Application? Application is just a class derived from the
NameObjectColle ctionBase class in the System.Collecti ons.Specialized
namespace.

Why not just implement a regular singleton (using the guidelines that
Jon pointed out, if you need lazy-load semantics)? After all, the
Application state is only applicable for the app domain on the local machine
(i.e. your web app), and a regular singleton would work just fine in this
scenario.

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"INeedADip" <IN*******@gmai l.com> wrote in message
news:ee******** ******@TK2MSFTN GP15.phx.gbl...
I want to get some feedback so don't hold back.

I have a webservice that is responsible for Formatting a ton of
information that is then queried by other applications (agents) that
utilize it (the info).
All this "formatting " and logic I am talking about needs to be done in a
centralized place and accessed by the agents. That is why we chose to go
with a web service.

Now...all this formatting needs to be done and held in memory so the
agents don't have to wait for it.
So we decided to implement a sort of singleton pattern...what do you guys
think?
Here is some sample code:

public class TheManager
{
private static object lockObject = new Object();
private const string CACHE_MANAGER = "Cache:Manager" ;
private List<InfoPacket > _preparedPacket s;

private TheManager() { initFunction(); }

public static InfoPacket GetInfoPacket() {
getManager().ge tInfoPacket(); }

public InfoPacket getInfoPacket() { ......some code ..... return
this._preparedP ackets[0] }

private static TheManager getManager()
{
object o =
System.Web.Http Context.Current .Application.Ge t(CACHE_MANAGER );
TheManager = oManager;
if(o == null)
{
lock(lockObject )
{
o =
System.Web.Http Context.Current .Application.Ge t(CACHE_MANAGER );
if (o == null)
{oManager = new TheManager();
System.Web.Http Context.Current .Application.Ad d(CACHE_MANAGER ,oManager);}
else oManager = (TheManager)o;
}
}
else oManager = (TheManager)o;

return oManager;

}

}

So now in our web service (*.asmx) we can call TheManager.GetI nfoPacket()
and a prepared packet is returned. Again, this is just a snippet of the
code..so we have functions and threads that are preparing the packet. We
are very consious of threading (utilizing lock() where needed). It has
performed VERY well and everything seems to be going as planned.

What do you guys think of a Singleton-esk pattern like the one above?

Jan 24 '06 #6
I agree with you on the naming conventions.... .I just typed that stuff out
to get the "Singleton" point across. Those aren't the actual names of the
classes...I also agree with the Property vs. Method statement (like we have
implemented). And I have now moved my "lock(lockObjec t)" per Jon's
suggestion.

My question was more about the Singleton-esk thing we have going..
You ask why we are storing the object in the Application State, but what is
another option?

As I understand it (probably wrong), the cache is per worker process...so
their could be more then one. And since the web service calls are
stateless, I thought we would need to store this in the Application State.

You said "a regular singleton would work just fine in this scenario"...but I
don't see how. I am not that experienced in Web Services, I tend to think
of them more like stateless aspx pages...Please let me know what you have in
mind...maybe we are going the wrong direction.
Jan 24 '06 #7
Still looking for constructive comments or and explination of what
Nicholas Paldino meant. How could a regular singleton work here? I
thought the stateless nature of ASP.NET (web and web services) would
prohibate using a regular singleton....

I've posted this on my blog to collect more comments:
http://ineedadip.blogspot.com/2006/0...rn-on-web.html

Jan 29 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
3469
by: Alicia Roberts | last post by:
Hello everyone, I have been researching the Singleton Pattern. Since the singleton pattern uses a private constructor which in turn reduces extendability, if you make the Singleton Polymorphic what sort of problems/issues should be considered? Also, I see that a singleton needs to be set up with certain data such as file name, database URL...
4
2412
by: Neil Zanella | last post by:
Hello, I would be very interested in knowing how the following C++ multi-instance singleton (AKA Borg) design pattern based code snippet can be neatly coded in Python. While there may be somewhat unusual places where multi-instance singleton is more useful than plain singleton, it seems to me that the former leads to less coding, so unless...
1
2028
by: Richard A. DeVenezia | last post by:
foo() generates elements with event handlers that invoke foo function properties. Is this an abhorrent or misthought pattern ? It allows just the one occurence of identifier /foo/ to be changed to /whatever/ when need arises and everything should still work. function foo () { var callee = arguments.callee
3
2473
by: Alicia Roberts | last post by:
Hello everyone, I have been researching the Singleton Pattern. Since the singleton pattern uses a private constructor which in turn reduces extendability, if you make the Singleton Polymorphic what sort of problems/issues should be considered? Also, I see that a singleton needs to be set up with certain data such as file name, database URL...
11
2161
by: Daniel Billingsley | last post by:
Let's say I'm writing a business app and I want there to be only one instance of the Customer object for each particular customer (representing a database record) being edited. Would it be possible to extend the Singleton pattern to handle this? Assuming that my Customer class follows the Singleton pattern (particularly Skeet's 4th...
21
2445
by: Sharon | last post by:
I wish to build a framework for our developers that will include a singleton pattern. But it can not be a base class because it has a private constructor and therefore can be inherit. I thought maybe a Template can be use for that, but C# does not support Templates (will be C# generics in mid 2005). Does anyone have a solution on how the...
13
3049
by: Robert W. | last post by:
At the beginning of my C# days (about 6 months ago) I learned about the Singleton pattern and implemented for Reference data, such as the kind that appears in an Options dialog box. My Singleton code looks like this: public sealed class Reference { private static readonly Reference instance = new Reference(); // Make the default...
2
6316
by: Kevin Newman | last post by:
I have been playing around with a couple of ways to add inheritance to a JavaScript singleton pattern. As far as I'm aware, using an anonymous constructor to create a singleton does not allow any kind of inheritance: singletonObj = new function() { this.prop = true; } Here are two ways to create a singleton with inheritance:
3
2955
by: dischdennis | last post by:
Hello List, I would like to make a singleton class in python 2.4.3, I found this pattern in the web: class Singleton: __single = None def __init__( self ): if Singleton.__single: raise Singleton.__single
3
18234
weaknessforcats
by: weaknessforcats | last post by:
Design Pattern: The Singleton Overview Use the Singleton Design Pattern when you want to have only one instance of a class. This single instance must have a single global point of access. That is, regardless of where the object is hidden, everyone needs access to it. The global point of access is the object's Instance() method. ...
0
7861
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7789
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8141
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8167
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5358
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3802
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3817
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1399
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1130
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.