Click here to Skip to main content
15,880,543 members
Articles / Web Development / ASP.NET
Tip/Trick

simple Asp.net singleton

Rate me:
Please Sign up or sign in to vote.
1.00/5 (2 votes)
26 Oct 2011CPOL 8.9K   2
simple Asp.net 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.



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

License

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


Written By
Software Developer (Senior)
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMarcus, Singleton means single instance and nothing more. In... Pin
rj4527-Oct-11 6:29
rj4527-Oct-11 6:29 
GeneralReason for my vote of 1 This is not a singleton. This is not... Pin
fjdiewornncalwe27-Oct-11 4:45
professionalfjdiewornncalwe27-Oct-11 4: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.