Click here to Skip to main content
13,249,504 members (39,237 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


Posted 26 Oct 2011

simple singleton

, 26 Oct 2011
Rate this:
Please Sign up or sign in to vote.
simple singleton
This creates a session singleton. In this example I am persisting a stringbuilder however you generally want a wrapper object in the case where you have two items that need persisting for that page. To generate the unique strings you can reflect the page name. Using this shows that you should rarely/never use Session.add ( within the same page context. ) Between pages will require some more error handling but will work as well. You can also use a per request session in some cases but that is beyond this sample.

/// <summary>
/// Persist the xml property as if it was a local variable.
/// </summary>
private StringBuilder xml
        return (HttpContext.Current.Session["UNIQUESTRINGHERE"] ??
        (HttpContext.Current.Session["UNIQUESTRINGHERE"] =
        new StringBuilder())) as StringBuilder;


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer (Senior)
Canada Canada
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMarcus, Singleton means single instance and nothing more. In... Pin
rj4527-Oct-11 7:29
memberrj4527-Oct-11 7:29 
Marcus, Singleton means single instance and nothing more. In we multiple scopes of singletons ( not just static ). You may be expecting simply static, which would be single instance server wide, however in that is rarely what we want. My example gives us a single instance per session which is a singleton of the session context. If you want it per Request then you could use HttpContext.Current.Items.add rather than session which is a singleton of the request scope.

As you know, If you want it accessible from throughout the application make the property public static.
GeneralReason for my vote of 1 This is not a singleton. This is not... Pin
Marcus Kramer27-Oct-11 5:45
memberMarcus Kramer27-Oct-11 5:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171114.1 | Last Updated 26 Oct 2011
Article Copyright 2011 by rj45
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid